Python __name__ = “__main__”

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

print(__name__) # prints __main__

If 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:

__name__ = '__main__'

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

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





Leave a Reply

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