name Variable

2 min read ·

What is name?

__name__ is a special built in variable in Python.
It tells how a Python file is being used:
  • Whether it is run directly
  • Or imported as a module

main Concept

When a Python file is executed directly, Python automatically sets:
When the same file is imported into another file, the value of __name__ becomes the module name.

Example

File: example.py

Case 1: Run directly

Output:

Case 2: Import in another file

Output:

Note

This behavior helps Python identify whether the file is the main program or just a module.


Why name is Used

It is used to control which part of code should run.
Without it, all code in a file runs even when imported.

Proper Usage


What Happens Here

  • If file runs directly → main() executes
  • If imported → main() does not execute

Pro Tip

Always wrap execution code inside a main function and use name check for better structure.


Real-world Usage

In real applications:
  • You write reusable functions in modules
  • You write test or execution code inside if __name__ == "__main__"
Example:
  • When imported → only functions are available
  • When run → test code executes

Real World Scenario

Developers use name to separate reusable logic from execution logic, especially in large projects and libraries.


Exercise

Create a file demo.py:
  • Define two functions
  • Add print statements inside main block
Import it into another file and observe which code runs.