Understanding Python's Name==Main
A Comprehensive Guide to the Name==Main Function in Python
Website Visitors:What is name == main
In Python, the special variable __name__
is a built-in variable that is automatically created and set by the Python interpreter. Its value depends on how the Python script is being executed.
When a Python script is executed, Python sets the __name__
variable to "__main__"
if the script is being run directly. However, if the script is imported as a module into another script, the __name__
variable is set to the name of the module (i.e., the filename without the .py
extension).
The common use case for __name__ == "__main__"
is to include code in a script that should only run when the script is executed directly (as the main program) and not when it is imported as a module into another script.
For example:
|
|
If you run my_script.py
directly, you’ll see the output "This script is being run directly"
and "This function is defined in my_script.py"
. However, if you import my_script.py
into another script, the block under if __name__ == "__main__":
won’t execute.
Here’s another example:
|
|
In this example, the my_function()
function is defined at the top level of the module, and will be executed whenever the module is imported by another program. However, the if __name__ == '__main__'
block ensures that my_function()
is only executed when the module is run as the main program.
So if you run this module as a script (e.g. python my_module.py
), it will print “Hello, world!”. But if you import it from another module (e.g. import my_module
), it will not execute the code inside the if __name__ == '__main__'
block.
Example
Here’s another example:
|
|
In this example, the math.py
module defines two functions, add()
and subtract()
, that can be used to perform addition and subtraction. The if __name__ == '__main__'
block at the bottom of the module ensures that these functions are only executed when math.py
is run as the main program.
So if you run this module as a script (e.g. python math.py
), it will print the results of calling the add()
and subtract()
functions. But if you import it from another module (e.g. import math
), it will not execute the code inside the if __name__ == '__main__'
block.
Where can you use name == main
Here are some examples where you might use __name__ == '__main__'
:
-
Command-line scripts: If you’re writing a Python script that is meant to be run from the command line, you can put the code that handles command-line arguments inside the
__name__ == '__main__'
block. For example:1 2 3 4 5 6 7 8 9 10 11 12
# my_script.py import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--name', type=str, help='Your name') args = parser.parse_args() print(f'Hello, {args.name}!') if __name__ == '__main__': main()
When you run this script from the command line (
python my_script.py --name Alice
), it will print “Hello, Alice!”. But if you import the script as a module from another script or a REPL, themain()
function will not be executed. -
Test modules: If you’re writing a module that contains test cases, you can put the test code inside the
__name__ == '__main__'
block. For example:1 2 3 4 5 6 7 8 9 10 11
# test_my_module.py import unittest import my_module class MyModuleTestCase(unittest.TestCase): def test_my_function(self): self.assertEqual(my_module.my_function(), 'Hello, world!') if __name__ == '__main__': unittest.main()
When you run this module as a script (
python test_my_module.py
), it will run the test case and report the results. But if you import the module from another test runner or a continuous integration pipeline, the test case will not be executed. -
Profiling code: If you’re writing code that you want to profile or measure performance, you can put the profiling code inside the
__name__ == '__main__'
block. For example:1 2 3 4 5 6 7 8 9 10 11 12
# my_module.py import time def my_function(): start_time = time.time() # ... some code ... end_time = time.time() print(f'my_function took {end_time - start_time:.2f} seconds to run.') if __name__ == '__main__': my_function()
When you run this module as a script (python my_module.py
), it will run the my_function()
and print the time it took to run. But if you import the module from another script or a REPL, the function will not be executed.
Suggested Article
If you’d like to continue reading, checkout our other python commands article here or browse all other topics here.
Conclusion
Overall, using the if __name__ == '__main__'
idiom helps to separate the code that is meant to be run as a standalone program from the code that is meant to be used as a library. This makes your code more modular and easier to reuse in different contexts.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.