Python - if__name__ == '__main__'

What is the __name__ variable?

__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below.

If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__“. If this file is being imported from another module, __name__14:09 2022/12/1 will be set to the module’s name.

How to use __name__ variable

Consider two separate files File1 and File2.

File1.py:

1
2
3
4
5
6
7
8
9
10

# File1.py

print ("File1 __name__ = %s" %__name__)

if __name__ == "__main__":
print ("File1 is being run directly")
else:
print ("File1 is being imported")

Now the interpreter is given the command to run File1.py.

$ python File1.py
Output :
File1 __name__ = __main__
File1 is being run directly

And File2.py, which imports File1.py:

1
2
3
4
5
6
7
8
9
10
11

# File2.py

import File1

print ("File2 __name__ = %s" %__name__)

if __name__ == "__main__":
print ("File2 is being run directly")
else:
print ("File2 is being imported")

Then File2.py is run.

$ python File2.py
Output :
File1 __name__ = File1
File1 is being imported
File2 __name__ = __main__
File2 is being run directly

Then we could add the if __name__ == '__main__' as the boilerplate code that protect us from invoking the imported scripts when we don’t intend to.

Rewrite the File1.py:

1
2
3
4
5
6
7
8
9
10
11

# File1.py

if __name__ == "__main__": ###key line
print ("File1 __name__ = %s" %__name__)

if __name__ == "__main__":
print ("File1 is being run directly")
else:
print ("File1 is being imported")

The re-run the File2.py

$ pyton File2.py
Output:
File1 is being imported
File2 __name__ = __main__
File2 is being run directly

The function in File1.py has not been run but imported.

https://www.geeksforgeeks.org/__name__-a-special-variable-in-python/

https://stackoverflow.com/questions/419163/what-does-if-name-main-do

https://www.freecodecamp.org/news/whats-in-a-python-s-name-506262fe61e8/

http://blog.castman.net/%E6%95%99%E5%AD%B8/2018/01/27/python-name-main.html


Python - if__name__ == '__main__'
http://arwenzhou.github.io/2022/12/01/Python-if-name-main/
Author
Arwen
Posted on
December 1, 2022
Licensed under