Yos Riady software craftsman 🌱

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

Yos is a software craftsman based in Singapore.

📬 Subscribe to my newsletter

Get notified of my latest articles by providing your email below.


Going Serverless book

Interested to find out more about serverless? Going Serverless 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 →