Yos Riady optimize for learning

Python __name__ == ‘__main__’

In this post I’d like to briefly mention a Python nicety:

if __name__ == '__main__':
    #execute some code

If you haven’t seen this before, that’s how a Python script checks if it’s been executed from the command-line, rather than just imported by another script.

Every line of code within the condition is only executed when the script is executed:

$ python myscript.py args

and not when the script is just imported:

>> from myscript import *

This way, you can distinguish between just importing your predefined methods and variables and actually executing your script using said methods and variables. Handy!

Author

You should follow him on Twitter.

📬 Get updates straight to your inbox!

Subscribe to my newsletter to make sure you don't miss anything.




Here's something you might be interested in...

Going Serverless book

Have you heard about the Serverless programming model? The Going Serverless book teaches you how to build scalable applications with the Serverless framework and AWS Lambda. You'll learn how to design, develop, test, deploy, and secure Serverless applications from planning to production.

Learn more →