what does if __name__ = ‘__main__’ mean

In recent practice, I see this appear a lot but I don’t know it.

The following video greatly explains this concept and I’d like to write down my notes here.

__name__ is a variable which is set value before other code is executed.

If the source file is run as the main program, __name__ ‘s value is ‘__main__’. Then main method is executed.

Otherwise, it means source file is imported, __name__’s value would be the name of the source file rather than ‘__main__’.

So in conclusion, this piece of code helps to tell if the module is main program or not.

But you can directly run the main method from imported file. Just put ‘imported module’.main() in your main program.

Leave a comment