I'm trying to write some (in my opinion) readable code in Python. I need a module that will contain a number of classes. Theoretically I know everything that is needed to accomplish this: I can simply put class definitions in a single module file.
For readability purposes I want to put every class definition into separate file (they are starting to be quite lengthy!), and all these classes into one directory. Whenever I create new file although it's contents are visible where I need them, class definition that's inside is scoped with unneeded module.
How should I do it? What is 'Python' way to do that?
Import them all within
__init__.py
, and then have the consumer import the package.If you want to avoid hardcoding full paths, file, class, and function names in many places, you could do something like the following which dynamically imports (almost) all the Python files it finds in a package's subdirectory.
The key is remembering that the
__init__.py
file is a largely unconstrained Python script itself, and is therefore free to perform fairly sophisticated processing of its own to determine what's in the package's namespace.File
package\__init__.py
:File
package\Class1.py
:File
package\Class2.py
:File
package\Class3.py
:File
usepackage.py
:Output from running
usepackage.py
: