What Does if name == “main”: Do in Python?
The if __name__ == "main"
is a guarding block that is used to contain the code that should only run went the file in which this block is defined is run as a script. What it means is that if you run the file as a script the `__name__variable will be equal to
'main'`.
Let’s look at an example:
mylib.py:
def say_hi():
print('hi from the function')
if __name__ == 'main':
print('the main block is being executed')
say_hi()
In the example above, we have defined a say_hi
function that will simply say hi when called. Then there is a guarded block with the if __name__ == 'main':
statement.
If you run the script in the console lie this:
python3 mylib.py
The output will be the following:
Output:
the main block is being executed
hi from the function
But if you include the mylib.py
file in some other python file and run that file as a script, you will see that the guarded block will not be executed.
other.py:
import say_hi from mylib
say_hi()
Output:
hi from the function
-
Scaling Python Applications
Learn everything you need to know about building, deploying and scaling python applications in production.
Guides -
What Does the “yield” Keyword Do in Python?
To better understand what yield does, you need first to understand what generator and iterable are. What is iterable When you use a list or list-like structure, you can read the values from the lis...
Questions -
Task scheduling in Python
Learn how to create and monitor Python scheduled tasks in a production environment
Guides
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github