Unlock Python’s __name__: When to Use It and Why It Matters
This article explains the purpose and behavior of Python's built‑in __name__ variable, showing how its value differs when a script is run directly versus when it is imported as a module, with clear code examples and execution flow diagrams.
You've probably seen the __name__ variable in many Python scripts; it often appears like this:
if __name__ == __main__:
main()In this article we dive into the built‑in __name__ variable, demonstrate how to use it in your Python modules, and explain what values it can take. __name__ is a special built‑in variable present in every Python module. Its value depends on how the code is executed: if the file is run directly, __name__ equals __main__; if the file is imported, __name__ equals the module's name.
Case 1 – Running the script directly
Assume we have nameScript.py with the following code:
def myFunction():
print("变量 __name__ 的值是 " + __name__)
def main():
myFunction()
if __name__ == __main__:
main()When you execute nameScript.py directly, Python first sets __name__ to __main__. The if condition evaluates to true, so main() runs and prints __main__.
Case 2 – Importing from another script
Now suppose we want to reuse myFunction() in another script called importingScript.py:
import nameScript as ns
ns.myFunction()When importingScript.py runs, the imported module nameScript has its __name__ set to nameScript, so the if condition inside nameScript.py is false and main() is not called. After the import, you can call ns.myFunction(), which prints the module's name ( nameScript).
In summary, the __name__ variable lets you distinguish whether a module is being run as a script or being imported, enabling you to write code that can act both as a reusable module and as a standalone program.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
