In this tutorial, we will explore the __name__ variable in Python and how it is used with the if __name__ == "__main__" idiom. Understanding these concepts is crucial for structuring your Python scripts effectively, distinguishing between scripts and modules, and implementing the main() function pattern.
When you run a Python script, Python assigns special names to certain variables. One of these is __name__. The value of __name__ depends on how the file is being used:
__name__ is set to '__main__'.__name__ is set to the name of the module.This distinction allows you to write code that behaves differently depending on whether it's being run directly or imported. The if __name__ == "__main__" idiom is a common pattern used to separate executable code from reusable code, making your scripts more modular and maintainable.
The __name__ variable is a built-in variable in Python that holds the name of the current module. When you run a Python file directly, it is considered the main program, and __name__ is set to '__main__'. If the same file is imported as a module in another script, __name__ will be set to the module's name.
Let's create a simple Python script named greeting.py.
1def greet():2print("Hello!")34if __name__ == "__main__":5greet()
When you run this script directly:
# No output
Using the if __name__ == "__main__" idiom helps you separate executable code from reusable code. This is particularly useful when you want to make your scripts both executable and importable.
Consider a script named calculator.py that defines a function for adding two numbers.
1def add(a, b):2return a + b34if __name__ == "__main__":5result = add(3, 4)6print(f"The sum is {result}")
You can run this script directly to see the output:
The sum is 11
Another common practice in Python is to define a main() function that encapsulates the executable code. This pattern enhances readability and makes your script more organized.
Let's refactor the previous calculator.py example to use the main() function pattern.
1def add(a, b):2return a + b34def main():5result = add(3, 4)6print(f"The sum is {result}")78if __name__ == "__main__":9main()
Running this script directly:
The sum is 11
if __name__ == "__main__" block is properly indented.__name__. It should be exactly __name__, not _name_ or name.main() function pattern, make sure to define the main() function before calling it.Let's create a complete example that combines all these concepts: an executable script with reusable functions and the main() function pattern.
Create a file named app.py.
1def greet(name):2return f"Hello, {name}!"34def add(a, b):5return a + b67def main():8name = "Alice"9greeting_message = greet(name)10print(greeting_message)1112result = add(10, 20)13print(f"The sum is {result}")1415if __name__ == "__main__":16main()
Run the script directly:
Hello, Bob! The sum is 40
| Concept | Description |
|---|---|
__name__ Variable | Holds the name of the current module. '__main__' when run directly. |
if __name__ == "__main__" | Idiom to separate executable code from reusable code. |
| Structuring Scripts vs Modules | Use if __name__ == "__main__" to make scripts both executable and importable. |
main() Function Pattern | Encapsulates executable code for better organization and readability. |
Now that you understand how to structure your Python scripts using the __name__ variable and the if __name__ == "__main__" idiom, you're ready to explore more advanced topics such as handling dates and times in Python. In the next tutorial, we will delve into the datetime module and learn how to work with dates, times, and time intervals.
Continue your journey by exploring Python Dates and Time.