Main Function
Understanding if __name__ == '__main__':
¶
In Python, if __name__ == '__main__':
is used to determine whether a script is run directly or imported as a module. This helps manage code execution depending on the context.
How It Works¶
-
Direct Execution: When you run a script directly (e.g.,
python my_script.py
),__name__
is set to'__main__'
. The code inside theif __name__ == '__main__':
block will run. -
Imported as a Module: When you import the script into another script (e.g.,
import my_script
),__name__
is set to the module's name (e.g.,'my_script'
). The code inside theif __name__ == '__main__':
block will not execute.
Examples¶
- Basic Example
Running python script1.py
will output "Hello!" because say_hello()
is called directly.
- Testing Functions
# script2.py
def add(a, b):
return a + b
if __name__ == '__main__':
result = add(2, 3)
print(f"Result: {result}")
Running python script2.py
will print "Result: 5". When imported, add()
can be used without printing the result.
- Module Import Example
Running python script4.py
will print "Hi, Bob!" but not "Hi, Alice!" since greet("Alice")
in script3
only runs when script3.py
is executed directly.
- Using Command-Line Arguments
# script5.py
import sys
def main():
if len(sys.argv) > 1:
print(f"Arguments: {sys.argv[1:]}")
else:
print("No arguments provided")
if __name__ == '__main__':
main()
Running python script5.py arg1 arg2
will print "Arguments: ['arg1', 'arg2']". When imported, main()
won't run automatically.
Takeaways¶
- Direct Execution: Code in
if __name__ == '__main__':
runs only when the script is executed directly. - Module Import: Code in this block does not run when the script is imported as a module.
- Use Cases: Ideal for testing code, running scripts, or executing code that should not run on import.
Using if __name__ == '__main__':
helps keep code modular and avoids unintended executions when scripts are imported as modules.