Understanding Python’s __main__ variable
Let’s say we have two scripts: foo.py and bar.py.
They are exactly the same. They begin with the definition of a function called main()
, which simply prints out the value of __name__
, a built-in variable that returns the name of the module.
If we run either of these modules, it will output ‘__main__’
. This tells us that a module refers to itself as ‘__main__’
.
Now let’s modify foo.py so that it imports bar.py. Now when we run foo.py, it first imports bar.py, which invokes its own main()
function. But, because it’s been imported, it now calls itself by its imported name: ‘bar’:
Then foo.py invokes its own main()
function, again calling itself ‘__main__’
.
It is common for modules to check to see if they are being imported by checking the value of the __name__
variable. And often, they’ll only run their main()
function if __name__
is equal to ‘__main__’
, indicating that they are not being imported
Video Version:
Related Articles
- Understanding Python’s __main__ variable (this article)
- How to find all your Python installations on Windows (and Mac)
- Associate Python Files with IDLE
- Python Virtual Environments with venv
- Mapping python to Python 3 on Your Mac