How to organize Python classes in modules and/or packages



Organizing Python classes into modules and/or packages depends a lot on personal preferences, convenience, readability and the application itself. There is always that case that each class is kept in a separate file. It may be that sometimes keeping related classes in one file may make it quite large while sometimes it may be just fine. So it all depends on the scenarios, convenience and ease of working with classes.

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__.

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. They are also run if the file is executed as a script. Modules can import other modules.

A collection of related modules providing one or more functionalities is called a package. So we can summarize and say that classes are organized into modules and packages in Python.




Advertisements