Python __name__ = “__main__”

When a python file is executed python foo.py, a hidden variable named __name__ is set to __main__

# foo.py
print(__name__) # prints __main__

If foo.py is imported using import foo, then the __name__ variable is set to foo

if __name__ = "__main__" is used to check whether the current file is being run standalone or being imported. You can certainly fool python by assigning __main__ to __name__ manually:

# foo.py
__name__ = '__main__'

if __name__ = '__main__':
    print('running standalone')

#bar.py
import foo.py

File bar.py imports foo.py, when foo gets loaded, it will think it is running standalone and thus, print out running standalone.

Reference

https://stackoverflow.com/a/419986/1478290
https://stackoverflow.com/a/419185/1478290

 
Bitnami