Understanding Python's __name__ Attribute

The name attribute in Python is a built-in variable that reveals how a script is being executed. When a file runs directly as the main program, name equals the string 'main'. Conversely, when the file is imported as a module in to another script, name holds the module's filename (with out the .py extension).

This behavior is commonly used to:

  • Execute code only when the script is the entry point.
  • Prevent certain code blocks from running during import, such as tests or demonstration code.
if __name__ == '__main__':
    print("This code runs as the main module.")
else:
    print("This code has been imported from another module.")

Practical Example

File: first.py

def hua():
    print("First function called successfully.")
def shu():
    print("Second function called successfully.")
def cao():
    print("Third function called successfully.")
def fun(n):
    print("__name__ in first.py:", __name__)
    return n

if __name__ == "__main__":
    print(fun(8))

File: second.py

import first

def fun2(n):
    return n * n

first.hua()
first.shu()
first.cao()
print("__name__ in second.py:", __name__)

if __name__ == "__main__":
    print(fun2(6))

Execution Analysis

When second.py runs as the main file:

  1. The import first statement triggers Python to execute first.py. Since it is imported (not the entry point), __name__ inside first.py becomes "first". The if __name__ == "__main__" bllock in first.py is skipped.
  2. fun2 is defined but not executed yet.
  3. The calls to first.hua(), first.shu(), and first.cao() each print their respective messages.
  4. print("__name__ in second.py:", __name__) outputs "__main__" because second.py is the entry point.
  5. The if __name__ == "__main__" condition is True, so fun2(6) is executed, printing 36.

This mechanism allows first.py to be used both as a standalone script (e.g., for testing) and as an importable module without unwanted side effects.

Tags: python __name__ module entry-point if __name__ == '__main__'

Posted on Tue, 04 Aug 2026 16:45:53 +0000 by krishna.p