NameError: name '__main__' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name __main__ is not defined in Python #

The Python "NameError: name __main__ is not defined" occurs when we forget to wrap the special name __main__ in quotes. To solve the error, wrap the name __main__ in quotes, e.g. "__main__".

nameerror name main is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name '__main__' is not defined. Did you mean: '__name__'? if __name__ == __main__: print('Module is run directly')

To solve the error we have to wrap the special name __main__ in quotes.

main.py
# ✅ using the string __main__ if __name__ == '__main__': # 👈️ wrap in quotes print('Module is run directly')

When a Python module is imported, the __name__ is set to the module's name.

main.py
import math print(math.__name__) # 👉️ "math"

Usually, this is the name of the Python file without the .py extension.

However, if the module is run directly, its __name__ is set to the string "__main__".

The __main__ name is the environment where top-level code is run. This is the first module that starts running (the entry point of our Python application).

Top-level means that this module imports all other files that the program needs.

You can use the __name__ variable to check if the module is running in the top-level environment.

main.py
if __name__ == '__main__': print('Module is run directly')

We compare the __name__ variable to the string "__main__" and if the condition is met, we know that the module is run directly and is not initialized from an import statement.

Conclusion #

The Python "NameError: name __main__ is not defined" occurs when we forget to wrap the special name __main__ in quotes. To solve the error, wrap the name __main__ in quotes, e.g. "__main__".

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.