What is __name__ == "__main__"?
In Python, `if __name__ == "__main__":` is a common idiom used to control the execution of code within a script. It allows a script to behave differently when it's run directly compared to when it's imported as a module into another script.
What is __name__?
Every Python module (a .py file) has a special built-in variable called __name__. This variable holds a string that indicates the current module's name. When a script is run directly from the command line, its __name__ variable is set to the string "__main__". However, if the script is imported into another module, its __name__ variable will be set to the module's actual file name (without the .py extension).
What does __name__ == "__main__" mean?
The condition if __name__ == "__main__": checks whether the current script is being executed as the main program. Code indented under this condition will only run if the script is the one being directly executed. If the script is imported as a module into another script, the code block under this condition will be skipped.
Why use it?
- Code Reusability: It allows you to put code that should only run when the script is executed directly (like calling a main function, parsing command-line arguments, or running tests) inside this block, while the rest of the module's functions and classes can be imported and reused by other scripts without automatically executing the main logic.
- Testing: You can include test cases or demonstration code within this block. When the module is imported, these tests won't run, but they will run if you execute the module directly.
- Clear Separation: It clearly separates the executable part of the script from the reusable components.
Example
def greet(name):
return f"Hello, {name}!"
def main():
print("This code runs only when the script is executed directly.")
print(greet("World"))
if __name__ == "__main__":
main()
else:
print("This module has been imported.")
In this example:
- If you run python your_script.py directly, __name__ will be "__main__", so main() will be called, printing "This code runs only..." and "Hello, World!".
- If another script imports this one (e.g., import your_script), then __name__ for this script will be "your_script". The if condition will be false, and "This module has been imported." will be printed instead. The greet function would still be available for the importing script to use (e.g., your_script.greet("Alice")).