What does if __name__ == "__main__" mean in Python

·

2 min read

I've searched the answer from stack overflow many times but until now I know exactly what it means. It is relevant to the concept of organizing the modules. We can introduce if __name__ == "__main__" after introducing how to organize modules in python.

When importing the module, we can easily initialize an instance if an object is created in the module, just like this:

class Database:
    pass

database = Database()

Then import the instance from another module:

from ecommerce.database import database

This will initialize the instance when importing the module, which is not ideal in some cases where the initialization of the app will be slowed. Therefore, we can add an initialization function to initialize the database when needed.

class Database:
    pass

database = None

def initialize_database():
    global database
    database = Database()

From the example above we know, codes will be executed when being imported, while the function won't unless it's used. We don't want certain codes to be run when being imported, so we introduce __name__. When the module is run directly, which means it is not imported, __main__ will be assigned to __name__. So we add if __name__ == "__main__": to indicate what to be run when the code is run by script rather than being imported.

To summarize: if __name__ == "__main__": means if the module is run by script rather than being imported, we run the coding in the following. Every module has a default property __name__ and when it is run by script, "__main__" will be assigned to the property.

Reference: Python 3 Object Oriented Programming by Dusty Phillips