Overview: Python __name__ Variable
In the previous tutorials, you learned how Python imports modules and how the import statement works. However, when a Python file is executed directly or imported into another program, Python automatically assigns a special value that affects how the file behaves. This behavior is controlled by the Python __name__ Variable.
In this tutorial, you will learn what the Python __name__ variable is, how Python assigns its value, and how that value changes when a file is run directly or imported as a module. Understanding this concept is essential before learning how the if __name__ == "__main__" statement works.
Quick Navigation
Use the links below to jump directly to any topic covered in this tutorial.
- Introduction: What is the Python
__name__Variable? - How Python Sets the
__name__Variable - Running a Python File vs Importing a Module
- Understanding the “
__main__” Value in Python - The
if __name__ == "__main__"Statement Explained - Why the Python
__name__Variable is Important - Practical Examples of the
__name__ - Real-World Example of the Python
__name__Variable - Common Mistakes When Using the Python
__name__Variable - Best Practices for Using the Python
__name__Variable - Key Takeaways: Python
__name__Variable
Introduction: What is the Python __name__ Variable?
The Python __name__ Variable is a special built-in variable that Python automatically creates whenever a Python file is executed or imported. It stores the name of the current module and helps Python identify how that file is being used.
The value stored in __name__ depends on how the Python file is executed:
- If the file is run directly, Python sets
__name__to"__main__". - If the file is imported into another Python program, Python sets
__name__to the module’s name.
This simple behavior allows a Python file to determine whether it is acting as the main program or as an imported module. As a result, programmers can control which parts of the code should run automatically and which parts should be available only when the module is imported.
Real-World Analogy
Imagine a teacher who visits different classrooms during the day. In one classroom, the teacher is the main instructor responsible for teaching the lesson. In another classroom, the same teacher is simply assisting another instructor.
Although it is the same person, the role changes depending on where they are working. The Python __name__ variable works in a similar way. It tells a Python file whether it is running as the main program or serving as a module inside another program.
How Python Sets the __name__ Variable
Unlike ordinary variables, the __name__ variable is not created by the programmer. Python automatically creates it before executing a Python file and assigns an appropriate value based on how that file is being used.
There are two possible values that beginners should understand:
"__main__"when the file is executed directly.- The module name when the file is imported into another Python program.
This assignment happens automatically every time a Python program starts. Programmers do not need to define or initialize the __name__ variable themselves.
Example: Displaying the Value of __name__
Create a Python file named example.py.
print(__name__)
If you run example.py directly, the output is:
__main__
Code Explanation
The print(__name__) statement displays the value currently stored in the special __name__ variable. Since the file is executed directly, Python automatically assigns the value "__main__", which is printed on the screen.
Later in this tutorial, you will see how this output changes when the same file is imported into another Python program.
Running a Python File vs Importing a Module
The value of the __name__ variable depends entirely on how a Python file is used. A file can either be executed directly or imported into another Python program, and Python assigns a different value to __name__ in each case.
| How the File is Used | Value of __name__ |
|---|---|
| The file is executed directly. | "__main__" |
| The file is imported as a module. | The name of the module |
This difference is one of the most important concepts in Python modules because it allows the same file to behave differently depending on whether it is the main program or an imported module.
Example
Suppose you have a Python file named message.py.
print(__name__)
Now create another Python file named main.py.
import message
Run main.py.
# Output
message
Code Explanation
When main.py imports message.py, Python treats message.py as a module instead of the main program. Therefore, Python assigns __name__ the value "message", which is the module’s name.
This behavior allows Python programs to identify whether a file is being executed directly or simply being imported for reuse. The next section explains why the special value "__main__" is used and how programmers take advantage of it.
Understanding the "__main__" Value in Python
When a Python file is executed directly, Python automatically assigns the special value "__main__" to the __name__ variable. This tells the program that the file is being run as the main program rather than being imported into another Python file.
If the same file is imported as a module, the __name__ variable does not contain "__main__". Instead, it stores the name of the module. This simple behavior allows a Python program to determine how it is being used.
How "__main__" Works
- If a file is executed directly,
__name__becomes"__main__". - If the file is imported,
__name__becomes the module’s name. - Programs can use this information to decide which code should execute.
The if __name__ == "__main__" Statement Explained
One of the most common patterns in Python is the if __name__ == "__main__" statement. It checks whether the current file is being executed directly or imported as a module.
If the condition is True, the code inside the if block runs. If the file is imported, the condition becomes False, and that block is skipped.
Syntax
if __name__ == "__main__":
# Code to execute only when the file is run directly
Example
calculator.py
def add(a, b):
return a + b
print(__name__)
if __name__ == "__main__":
print(add(10, 20))
Running calculator.py
__main__
30
Code Explanation
Since calculator.py is executed directly, Python assigns "__main__" to the __name__ variable. The condition evaluates to True, so the add() function is called and the result is printed.
Importing the Same Module
main.py
import calculator
Output
calculator
Code Explanation
When calculator.py is imported, the value of __name__ becomes "calculator" instead of "__main__". As a result, the condition is False, so the code inside the if block does not execute.
Why the Python __name__ Variable is Important
The Python __name__ Variable allows a program to determine whether it is being executed directly or imported as a module. This makes Python files more reusable because the same file can contain both reusable functions and executable code.
Some of the main benefits of using the __name__ variable include:
- Prevents demonstration or testing code from running when a module is imported.
- Makes modules reusable across multiple programs.
- Keeps reusable functions separate from executable code.
- Improves code organization and maintainability.
- Supports better testing and debugging practices.
Real-World Example of the Python __name__ Variable
Imagine a television that can operate in two different modes. When you press the power button on the TV itself, it starts normally and displays its home screen. However, when another device, such as a gaming console, connects to the TV, the television behaves differently and simply provides its display without launching its own startup activities.
The __name__ variable works in a similar way. When a Python file runs directly, __name__ becomes "__main__", allowing the program to execute its main code. When the same file is imported into another program, Python assigns the module’s name to __name__, so only its reusable functions, classes, and variables become available without executing the main program.
Common Mistakes When Using the Python __name__ Variable
Although the Python __name__ Variable is straightforward, beginners often make a few common mistakes while learning how it works. Understanding these mistakes will help you write cleaner and more reliable Python programs.
The most common mistakes include:
- Forgetting Double Underscores
- Writing
__main__Without Quotes - Expecting the
if __name__ == "__main__"Block to Run After Importing - Placing Reusable Functions Inside the
ifBlock
The following sections explain each mistake, why it happens, and how to avoid it.
1. Forgetting Double Underscores
The variable name is __name__, with two underscores before and after name. Writing _name_ or name refers to a completely different variable.
print(name)
# Output
NameError: name 'name' is not defined
Correct code:
print(__name__)
2. Writing __main__ Without Quotes
The value "__main__" is a string. Forgetting the quotation marks causes Python to treat it as a variable instead of a string.
if __name__ == __main__:
print("Program started")
Correct code:
if __name__ == "__main__":
print("Program started")
3. Expecting the if __name__ == "__main__" Block to Run After Importing
The code inside the if __name__ == "__main__" block runs only when the file is executed directly. It does not run when the file is imported as a module.
4. Placing Reusable Functions Inside the if Block
>
Functions and classes that other programs need should be defined outside the if __name__ == "__main__" block. Otherwise, they may not be available when the module is imported.
Best Practices for Using the Python __name__ Variable
Following a few simple practices will help you use the __name__ variable correctly and create Python modules that are easier to reuse and maintain.
- Use
if __name__ == "__main__"for code that should run only when the file is executed directly. - Keep reusable functions, classes, and variables outside the
ifblock. - Use the
if __name__ == "__main__"block for testing, demonstrations, or calling the main function of your program. - Write modules so they can be imported without producing unwanted output.
- Keep the code inside the
if __name__ == "__main__"block short and focused on starting the program. - Use descriptive function names and organize reusable code clearly to improve readability.
Key Takeaways: Python __name__ Variable
Here are the key points to remember about the Python __name__ Variable.
- The
__name__variable is automatically created by Python for every module. - When a file is executed directly,
__name__is assigned the value"__main__". - When a file is imported,
__name__stores the module’s name. - The
if __name__ == "__main__"statement controls code that should run only when a file is executed directly. - Using the
__name__variable helps create reusable, organized, and maintainable Python modules. - Following good practices prevents unwanted code from running when modules are imported.
You now understand how the Python __name__ variable works and why the if __name__ == "__main__" statement is widely used in Python programs. In the next tutorial, you will learn how Python packages organize related modules into a structured and reusable project.