Wed Apr 20 2022·1 min read
Photo by Raychan
__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.
Here is an example of how the error occurs.
# ⛔️ 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.
# ✅ 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.
import math print(math.__name__) # 👉️ "math"
Usually this is the name of the Python file without the
However, if the module is ran directly, its
__name__ is set to the string
__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
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.