__name__

A module's name as a string, or '__main__' in the module that was run directly.

In more detail

Python sets __name__ in every module. When a file is run as the program it is '__main__'; when the file is imported it is the module's own name, such as 'greet' or 'shop.cart.total'. The guard if __name__ == '__main__': keeps tests and demos from running when the module is imported.

Example

def hello():
    return 'hi'

if __name__ == '__main__':
    print(hello())

Related terms

Taught in

References

Certification courses