Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

What is the purpose of `if __name__ == '__main__'`?

+17
−0

I often see the construct if __name__ == '__main__' in Python code. For example, the queens.py demo in the Python repository ends with these two lines:

if __name__ == "__main__":
    main()

However, the beer.py demo does not. Both run just fine and display things in the console. Moreover, if I remove the if __name__ == "__main__" line in queens.py (and unindent the call of the main() function), it still works, nothing changed. When code is non-functional, I'd rather remove it…

So what's the purpose of that construct? When it is useful, and when is it not?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

1 answer

+21
−0

It makes difference if the script is being imported.

Let's suppose I have a file my_file.py:

# my_file.py
def some_function():
    print('do some stuff')

print('calling function:')
some_function()

If I execute it directly (such as python my_file.py), the output is:

calling function:
do some stuff

Now suppose that I have another file (another.py), that imports my_file.py and uses some_function:

# another.py
import my_file

print('calling function from my_file')
my_file.some_function()

By executing python another.py, the output will be:

calling function:
do some stuff
calling function from my_file
do some stuff

That's because the import executes the whole contents of my_file.py (producing the first two lines in the output), and then another.py calls the function again.

To avoid that, we can change my_file.py to this:

# my_file.py modified
def some_function():
    print('do some stuff')

if __name__ == "__main__":
    print('calling function:')
    some_function()

If I execute it directly (python my_file.py), it still executes the two lines inside the if (print and some_function()).

But if I execute python another.py, the output will be:

calling function from my_file
do some stuff

Because when my_file.py is imported, the code inside that if is not executed.


That happens because, when a Python source file is executed, some special variables are set, and __name__ is one of them.

When the file is being executed directly (such as python my_file.py), the __name__ variable is set to __main__. But when my_file.py is imported, its __name__ variable is set to my_file.

Let's modify the files to see how this works.

my_file.py:

print('my_file=', __name__)

another.py:

import my_file

print('another=', __name__)

If I execute python my_file.py, the output is:

my_file= __main__

But if I execute python another.py, the output is:

my_file= my_file
another= __main__

Note that, for the file being executed, the __name__ variable contains the value __main__, and for the imported files, the __name__ variable is the file's name without the .py extension.

The code above also shows that each module has its own __name__. This means that another.py could also have the same if clause inside it, to check if it's being imported, regardless of other module's __name__'s.


This is useful when a module contains lots of functions/classes that you want to import and use, but it also contains a "main" part that acts as a script by itself (this could be the main program, or unit tests, or a "demo" for the functions, or whatever). This "main" part can be put inside that if clause, so you don't run it when the module is imported, as in this case you're interested only in reusing the functions/classes.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

1 comment thread

There are some other use cases besides reusing functions and classes: 1) Debugging: You can import... (1 comment)

Sign up to answer this question »