- Python Snacks
- Posts
- What is __name__ == "__main__"?
What is __name__ == "__main__"?
See how this can affect your Python code during run time.
When it comes to writing Python scripts, you may have encountered the __name__ == "__main__" line of code.
This line of code is not just a convention—it plays a crucial role in how Python scripts are executed, especially in larger, more complex projects.
So, this begs the question: What does this do, and why is it something you should include in your source code?
To understand this, we first need to understand what __name__ is.
Article Contents
How Python executes code
When a Python script is invoked, it compiles the source code into bytecode, then in which the Python interpreter executes (hence the __pycache__ directory you see in your project).
Python has several variables and functions that are built-in that are a part of the environment, such as __file__, __doc__, and __package__.
One of these variables is __name__, which is the variable that represents the name of the module that is being run. By default, the script that is being invoked is set to main.
» In practice, you don’t have to set this variable, as Python will do this automatically.
Behavior of __name__ == “__main__”
When we see the following in a Python script:
def my_function():
print("Hello, world!")
if __name__ == "__main__":
my_function()
All it is is flow control - it’s an if statement with a boolean. The comparison will evaluate to be True if and only if this script is:
Invoked directly (by clicking the “run” button or command line)
__name__ is set to __main__ at the top of the script in the code (which you shouldn’t do).
Example with __name__ == “__main__”
While I did provide an example above, it really doesn’t showcase how this works. Suppose we have the following script, called pyfile.py
:
def my_function():
print("--> Function was called.")
print("--> This module was imported.")
if __name__ == '__main__':
print("--> This was ran directly!")
Let’s say that we were to invoke the script through the command line directly:
bmolyneaux@Brandons-MacBook-Pro ~ % python pyfile.py
—> This module was imported.
—> This was ran directly!
The conditional statement was True. That is because, in this case, __name__ was set to __main__, as we invoked the script directly.
However, if we import it to another file (say second.py
):
import pyfile as p
p.my_function()
And then invoke it on the command line:
bmolyneaux@Brandons-MacBook-Pro ~ % python second.py
—> This module was imported.
—> Function was called.
Notice that this time, it didn’t print out “—> This was ran directly!“. This is because the __name__ variable for pyfile.py
was set to __pyfile__, as it was imported and not invoked directly.
That’s all for today’s snack. Happy coding!
📧 Join the Python Snacks Newsletter! 🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.
Reply