Python __name__ Variable – Tutorial with Examples

In Python, the special variable __name__ is used to determine if a Python script is being run as the main program or as an imported module. When a Python script is executed, the __name__ variable is automatically set to "__main__" if the script is the main program. If the script is imported as a module, the __name__ variable is set to the name of the module.

Example 1: Running a Python Script as the Main Program

# main.py
def main():
    print("This is the main function")

if __name__ == "__main__":
    main()

In this example, the main() function is defined and the if __name__ == "__main__": statement is used to check if the script is being run as the main program. If it is, the main() function is executed, and the output is:

This is the main function

Example 2: Importing a Python Script as a Module

# main.py
def main():
    print("This is the main function")

if __name__ == "__main__":
    main()

# import.py
import main

In this example, the main.py script is imported as a module into another Python script called import.py. When the import.py script is executed, the main.py script is imported, but the if __name__ == "__main__": statement is not executed, so the main() function is not executed and there is no output.

Conclusion

The __name__ variable is a powerful and versatile tool in Python that allows you to determine if a script is being run as the main program or as an imported module. This can be useful in a variety of applications and can help you write cleaner, more organized, and more maintainable code.

Leave a Reply

Your email address will not be published. Required fields are marked *