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. foo and bar

If we run either of these modules, it will output ‘__main__’. This tells us that a module refers to itself as ‘__main__’. foo and bar with output

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’: foo and bar import

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 foo and bar with if

Video Version:

Written by Nat Dunn. Follow Nat on Twitter.


Related Articles

  1. Understanding Python’s __main__ variable (this article)
  2. How to find all your Python installations on Windows (and Mac)
  3. Python Virtual Environments with venv
  4. Mapping python to Python 3 on Your Mac