Fix - NameError: name '__main__' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Raychan

Fix - 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 ran 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 ran 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 ran directly, its __name__ is set to the string "__main__".

The __main__ name is the environment where top-level code is ran. 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 ran directly')

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

Use the search field on my Home Page to filter through my more than 1,000 articles.