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:
- The
import firststatement triggers Python to executefirst.py. Since it is imported (not the entry point),__name__insidefirst.pybecomes"first". Theif __name__ == "__main__"bllock infirst.pyis skipped. fun2is defined but not executed yet.- The calls to
first.hua(),first.shu(), andfirst.cao()each print their respective messages. print("__name__ in second.py:", __name__)outputs"__main__"becausesecond.pyis the entry point.- The
if __name__ == "__main__"condition is True, sofun2(6)is executed, printing36.
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.