re: What's the use of if __name__ == '__main__': in Python? VIEW POST


The main reason is because importing a module runs it. However, a module's __name__ attribute is only set to "__main__" if it was executed directly, instead of imported.

Thus, you can write a module to run by itself, but also import it without having it try to run as if it were the main script.

Consistency is important besides, so we just conventionally use the if __name__ == '__main__': syntax, even if we don't think we'll need it. There are exceptions, but you should default to using it until you have a reason not to.

code of conduct - report abuse