Using __name__
in Practice
Now that you understand the concept of the __name__
variable and how it can be used to identify the main module, let's explore some practical examples of how to use it in your Python code.
Executing Initialization Code
One common use case for the __name__
variable is to execute initialization code or setup tasks only when the script is the main program, and not when it's imported as a module. This can be useful for tasks like setting up logging, configuring the environment, or running tests.
Here's an example:
## app.py
import logging
## Set up logging
logging.basicConfig(level=logging.INFO)
if __name__ == "__main__":
logging.info("This script is being run as the main program.")
## Add any other initialization code or tasks here
else:
logging.info("This script is being imported as a module.")
In this example, the logging configuration is set up regardless of whether the script is the main program or being imported as a module. However, the message logged depends on the value of the __name__
variable.
Running Tests
Another common use case for the __name__
variable is to run tests only when the script is executed directly, and not when the module is imported. This ensures that the test code is not accidentally executed when the module is used in a different context.
Here's an example:
## test_app.py
import unittest
class TestApp(unittest.TestCase):
def test_something(self):
self.assertEqual(1, 1)
if __name__ == "__main__":
unittest.main()
In this example, the test code is only executed when the test_app.py
script is run directly, and not when it's imported as a module.
Providing a Command-Line Interface
The __name__
variable can also be used to provide a command-line interface (CLI) for your module. By checking the value of __name__
, you can determine whether the script should run the CLI or provide module-level functionality.
Here's an example:
## my_module.py
import sys
def do_something():
print("Doing something as a module.")
if __name__ == "__main__":
if len(sys.argv) > 1:
command = sys.argv[1]
if command == "do-something":
do_something()
else:
print(f"Unknown command: {command}")
else:
print("Usage: python my_module.py do-something")
In this example, if the my_module.py
script is run directly, it checks the command-line arguments and executes the appropriate functionality. If the script is imported as a module, the do_something()
function can be used directly.
By understanding and utilizing the __name__
variable, you can write more flexible and maintainable Python code that can be used both as a standalone program and as a reusable module.