What’s with the __name__ variable in Python?
If you're learning Python, it's important to understand how the __name__ variable can help you avoid creating bad modules.
Published Mar 26, 2024
If you get a bit confused when you see this:
if __name__ == '__main__':
Don’t worry, it’s easy. 😎
There are two ways of executing a Python script: as an application or as a module.
If you run a Python script directly then you are executing it as an application, like so:
F:\codingmatheus\dev\snippets\whats_with_name_variable> py demo1.py
However, you can also import your Python scripts from another one instead of running them directly. When you do this, it is said that you are executing that script as a module, like so:
import demo1
In both cases, Python will execute all of the code inside the script, the only difference is when they get executed.
When you run it as an application then it gets execute right away, but when you import it as a module then Python will automatically execute it for you every time it encounters that import statement.
That can lead to unexpected results if you have code that is not contained inside classes or functions. For example, if the code inside demo1.py was only a print statement like this:
print("Hello, demo1!")
Then, when I import demo1.py into another script that statement would be printed as part of my application output which is not what I want. I would have to dig through my code to figure out where that was coming from which can be difficult specially when your codebase is large and you’re also importing lots of modules.
So we want to make sure that that print() statement is only run when demo1.py is executed directly and that’s where the __name__ variable comes.
“__name__” is a special variable managed by Python and it will automatically set its value to “__main__” if the script is being run directly and to the name of the module, that is, its filename, if it is just being automatically executed as part of an import statement.
So we can change demo1.py to become a module that is safe to be imported by others by checking that __name__ variable like so:
import logging
if __name__ == '__main__':
print("Hello, demo1!")
else:
logging.info(f"{__name__} was imported as module by another Python script.")
Note that I used the logging function to output the module’s name so I can still output messages that I think is important from my script without being disruptive to the application that is importing it.
Of course, if you have you code tucked inside classes or functions then you don’t have to worry about anything since those have to be instantiated and called explicitly.
However, always make sure to wrap any code outside of those within that if statement and take extra care to not cause any obscure bugs in that application importing your scripts or slow down performance by executing unnecesary code.