Python Mastery – From Basics to Brilliance / Modules & Packages

__name__

🏷️ __name__

__name__ is a special variable that tells Python the name under which a file (module) is being used.

The most important thing to understand is that its value changes depending on how the Python file is run.


▢️ When You Run the File Directly

Suppose we have a file called calculator.py:

print(__name__)

If you run:

python calculator.py

Python sets:

__name__ = "__main__"

So the output is:

__main__

πŸ‘‰ The file being run directly is always called "__main__" by Python.


πŸ“¦ When You Import the File

Suppose calculator.py contains:

print(__name__)

And another file contains:

import calculator

Now calculator.py is not being run directly. It is being imported.

So Python sets:

__name__ = "calculator"

Output:

calculator

πŸ”‘ Why if __name__ == "__main__"?

Consider:

# calculator.py

def add(a, b):
    return a + b

if __name__ == "__main__":
    print(add(10, 5)) #15

If we import calculator.py:

import calculator

Now:

__name__ == "calculator" is False
print(add(10, 5)) does NOT run

But we can still use:

print(calculator.add(10, 5))

🧠 Think of It Like This

Therefore:

if __name__ == "__main__":

means:

"Run this code only if this file is being executed directly, not when it is imported."

⭐ Remember

__name__ β†’ Tells Python how the current file is being used.

"__main__" β†’ The file is being run directly.