Zone Of Makos

Menu icon

__name__ in Python

The __name__ attribute is a special built-in variable in Python that is used to determine whether a module is being run as the main program or imported as a module. It can be used to add functionality to a module when it is run as the main program, but not when it is imported as a module. In this lesson, we'll explore how to use __name__ in Python and why it is a useful feature.

Using __name__ in Python

When a Python module is imported, its code is executed and the resulting objects are added to the importing module's namespace. However, when a module is run as the main program, its code is executed in a separate namespace. This is where __name__ comes in. By checking the value of __name__ at runtime, you can determine whether the module is being run as the main program or imported as a module.


if __name__ == "__main__":
    # Code to run when module is run as the main program
    print("This code is running as the main program")
else:
    # Code to run when module is imported as a module
    print("This code is running as a module")

In this example, the code inside the if __name__ == "__main__": block will only be executed if the module is run as the main program. Otherwise, the code inside the else block will be executed when the module is imported as a module.

Why use __name__ in Python

Using __name__ in Python can be useful for separating code that is intended to be run as the main program from code that is intended to be imported as a module. It can also be used to add functionality to a module when it is run as the main program, but not when it is imported as a module. For example, you might want to include some sample code or test cases in a module, but you don't want that code to be executed when the module is imported.

Conclusion

__name__ is a special built-in variable in Python that is used to determine whether a module is being run as the main program or imported as a module. By using __name__ in your Python code, you can separate code that is intended to be run as the main program from code that is intended to be imported as a module, and add functionality to a module when it is run as the main program, but not when it is imported.