39. Python's __main__ Convention

The __main__ convention in Python is a commonly used pattern that allows a module to be executed both as a standalone script or imported as part of another module. This is accomplished by using the if __name__ == "__main__": statement, which checks whether the module is being run directly or imported.

Here are 10 Python snippets demonstrating different ways to use this convention:


1. Basic __main__ Convention

This example shows how to write a simple script that can be executed directly or imported without running the script code.

# script.py
def greet():
    print("Hello, World!")

if __name__ == "__main__":
    greet()

When you run script.py directly (python script.py), it will print "Hello, World!". If you import it, nothing happens.


2. Using __main__ for Execution Control

You can control which code should be executed when a script is run directly versus when it's imported.

# mymodule.py
def say_hello():
    print("Hello from mymodule!")

if __name__ == "__main__":
    print("Running mymodule directly.")
    say_hello()
else:
    print("mymodule imported.")

When mymodule.py is imported, it prints "mymodule imported.". When executed directly, it prints "Running mymodule directly." followed by "Hello from mymodule!".


3. Accepting Command-Line Arguments in __main__

This example shows how you can accept command-line arguments using sys.argv when the module is run directly.

Run the script with arguments: python script.py arg1 arg2, and it will print the arguments passed to it.


4. Using argparse for Command-Line Parsing

A more sophisticated version using argparse for command-line argument parsing.

When run with: python script.py 5, it will print the received number 5.


5. Combining Functions in __main__ Block

This shows how to execute multiple functions only when the script is run directly.

Running the script will execute both function_a() and function_b(), but importing the script won't.


6. Testing Module Functionality with __main__

You can use the __main__ block to test the module's functionality without executing it when imported.

When module.py is run directly, it prints the test result. When imported, the add() function is available but nothing is printed.


7. Logging with __main__

This example demonstrates adding logging functionality in the __main__ block.

When executed, this sets up logging and outputs log messages.


8. Running Tests in __main__

You can use the __main__ block to run tests directly when needed.

Running the script will run the test function test_add(), but importing the script won't execute it.


9. Building a Simple CLI with __main__

You can combine the __main__ block and argparse to create a simple command-line interface.

When run with: python script.py Alice, it will output Hello, Alice!.


10. Python Module with __main__ for Testing

This shows a module with a testable function and a __main__ block to test its behavior.

Running the script directly will output the result of 5 * 4.


These snippets demonstrate how to use the __main__ convention to create versatile modules that can either be run directly as scripts or imported without executing the script-specific code.

Last updated