Skip to content

Python __name__ and __main__

We often see Python code like this:

if __name__ == "__main__":
    main() 

In Python, __name__ and __main__ are two special variables related to module and script execution.

__name__ and __main__ are typically used to control how code is executed, especially when a module can be run as a standalone script or imported by other modules.

__name__ is a built-in variable used to represent the name of the current module.

The value of __name__ depends on how the module is used:

When the module is run as the main program: the value of __name__ is set to “__main__”.

When the module is imported: the value of __name__ is set to the module’s filename (excluding the .py extension).

Suppose we have a module.py file:

print(f"Module's __name__ value: {__name__}")

The output would be:

Module's __name__ value: __main__

__main__ is a special string used to indicate that the current module is being run as the main program.

__main__ is typically used together with the __name__ variable to determine whether a module is being imported or run as a standalone script.

3. The Common Pattern of if __name__ == “__main__”:

Section titled “3. The Common Pattern of if __name__ == “__main__”:”

In Python, it is common practice to add the following code block at the end of a module:

if __name__ == "__main__":
    # Code here will only execute when the module is run as the main program
    main()

This pattern allows the module to not execute certain code when imported, and only execute that code when run as a standalone script.


Suppose we have a module named example.py:

def greet():
    print("Greetings from the example module!")

if __name__ == "__main__":
    print("This script is being run directly.")
    greet()
else:
    print("This script is being imported as a module.")

If you run example.py directly, the output will be:

This script is being run directly.
Greetings from the example module!

In this case, the value of __name__ is “__main__”, so the code in the if __name__ == “__main__”: block is executed.

If you import example.py in another script, for example:

# another_script.py

import example

example.greet()

The output will be:

This script is being imported as a module.
Greetings from the example module!

In this case, the value of __name__ is “example” (the module name), so the code in the if __name__ == “__main__”: block is not executed.

  • __name__ is a built-in variable that represents the name of the current module.

  • When the module is run as the main program, the value of __name__ is "__main__".

  • When the module is imported, the value of __name__ is the module’s filename.

  • Using if __name__ == "__main__": controls whether certain code is executed when the module is imported, and only executes that code when running as a standalone script.