It helps your Python file know if it is being run directly or being used by another file. This way, you can control what code runs in each case.
0
0
__name__ and __main__ behavior in Python
Introduction
You want to test parts of your code by running the file directly.
You want to write reusable code that can be imported without running test code.
You want to organize your program so some code only runs when you start the file.
You want to avoid running certain code when your file is imported by others.
Syntax
Python
if __name__ == "__main__": # code to run only when file is executed directly print("Running directly")
__name__ is a special variable Python sets automatically.
When you run a file directly, __name__ equals "__main__".
Examples
This prints the value of
__name__. If run directly, it prints __main__ and the message.Python
print(__name__) if __name__ == "__main__": print("This runs only when executed directly")
If you run
mymodule.py directly, it calls greet(). If imported, it does not run greet() automatically.Python
# file: mymodule.py def greet(): print("Hello!") if __name__ == "__main__": greet()
Sample Program
This program shows the value of __name__. If you run this file directly, it prints the message from main(). If you import it, only the print line runs showing the module name.
Python
def main(): print("This code runs only when the file is executed directly.") print(f"The __name__ variable is: {__name__}") if __name__ == "__main__": main()
OutputSuccess
Important Notes
When imported, __name__ equals the file name (without .py), not __main__.
This behavior helps separate reusable code from test or script code.
Summary
__name__ tells if a file is run directly or imported.
Use if __name__ == "__main__" to run code only when the file is executed directly.
This makes your code cleaner and more reusable.