Understanding the __name__ Variable in Python
While learning Python, I discovered the __name__ variable and its significance in script execution. Here's what I learned:
What is __name__?
__name__ is a special variable in Python used internally by the interpreter. Its value depends on how the script is executed:
- When the script is run directly:
__name__is set to"__main__". - **When the script is imported as a module,
__name__is set to the module's name.
This allows developers to control the behaviour of a script when executed directly versus when imported.
Code Example
one.py
# one.py
def func():
print("func() ran in one.py")
print("top-level print inside of one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print(f"one.py is being imported into another module {__name__}")
two.py
# two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
three.py
import two
import one
print("top-level in three.py")
if __name__ == "__main__":
print("three.py is being run directly")
Output
Running one.py directly:
top-level print inside of one.py
one.py is being run directly
Running two.py:
top-level print inside of one.py
one.py is being imported into another module one
top-level in two.py
func() ran in one.py
two.py is being run directly
Running three.py
top-level print inside of one.py
one.py is being imported into another module one
top-level in two.py
func() ran in one.py
top-level in three.py
three.py is being run directly
Observations
Behaviour of Code Execution:
-
When running
one.pydirectly:- All code at 0 indentation is executed.
- The block
if __name__ == "__main__":runs because__name__is"__main__".
-
When running
two.py:- The 0 indentation code in
one.pyruns because it's imported intotwo.py. - Since
__name__inone.pyis the module name ("one"), theelseblock is executed. - Afterwards, the 0 indentation code in
two.pyexecutes, including callingfunc()fromone.py. - Finally, the
if __name__ == "__main__":block intwo.pyruns because it is the main program.
- The 0 indentation code in
-
When running
three.py:- The 0 indentation code in
one.pyruns because it’s imported viatwo.py. - Since
__name__inone.pyis"one", theelseblock executes. - The 0 indentation code in
two.pyexecutes next, including callingfunc()fromone.py. - The 0 indentation code in
three.pyexecutes last. - The
if __name__ == "__main__":block inthree.pyruns.
- The 0 indentation code in
Key Takeaways
- The
__name__variable helps differentiate between direct execution and import behaviour. - The
if __name__ == "__main__":block ensures that code only runs when the script is executed directly.
Sequence of Execution
- Code at 0 indentation runs immediately when a module is imported.
- Once a module has been loaded, it won’t execute again even if explicitly re-imported.