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

  1. Direct Execution: When you run a script directly (e.g., python my_script.py), __name__ is set to '__main__'. The code inside the if __name__ == '__main__': block will run.

  2. 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 the if __name__ == '__main__': block will not execute.

Examples

  1. Basic Example

    # script1.py
    def say_hello():
        print("Hello!")
    
    if __name__ == '__main__':
        say_hello()
    

    Running python script1.py will output “Hello!” because say_hello() is called directly.

  2. 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.

  3. Module Import Example

    # script3.py
    def greet(name):
        print(f"Hi, {name}!")
    
    if __name__ == '__main__':
        greet("Alice")
    
    # script4.py
    import script3
    
    script3.greet("Bob")
    

    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.

  4. 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.