__name__

What does if __name__ == "__main__": do?

Here's a best answer in stackoverflow: __name__ explanation

A practice about the main check:

maincheck1.py:

def function1():
    print("This is a __name__ practice.")

if __name__ == "__main__":
    print("This script is being run by itself.")
else:
    print("I am being imported into other modules.")

maincheck2.py:

import maincheck1

maincheck1.function1()

output:

Summary: A module's __name__ is set to "__main__" when read from standard input, a script, or from an interactive prompt.

A reason for doing this is that sometimes you write a module, and it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

results matching ""

    No results matching ""