Skip to content
Home / Fundamentals

What does if __name__ == "main" do?

In Python, the __name__ special attribute is a built-in variable that returns the name of the current module. If a module is being run directly (as in python mymodule.py), __name__ is set to "__main__". This can be useful for determining whether a module is being run directly or being imported by another module.

Here is an example of how __name__ can be used to execute code only when a module is run directly:

def main():
    # Code to run when module is run directly
    print("This code is only run when the module is run directly.")

if __name__ == "__main__":
    main()

In this example, the main() function will only be executed if the module is run directly. If the module is imported by another module, the main() function will not be executed.

Here is another example that demonstrates how __name__ can be used to import and use functions from another module:

# mymodule.py

def main():
    print("This code is only run when the module is run directly.")

def func():
    print("This is a function in the module.")

if __name__ == "__main__":
    main()

# main.py

import mymodule

mymodule.func()

In this example, the main() function in mymodule.py will only be executed if the module is run directly. However, the func() function can still be imported and used by another module (in this case, main.py).

It is important to note that __name__ is not a keyword and should not be surrounded by quotes (e.g. __name__ == "__main__" is correct, while "__name__" == '__main__' is incorrect).