pythondesign-patternspython-importpython-module

"Collecting" classes/variables from various files to simplify importing?


Suppose several classes are defined in multiple different files across a Python project, such as

mylib.somefile.Class1
mylib.somefile.Class2
mylib.anotherfile.Class3
mylib.athirdfile.Class4
...

What would be the best way to aggregate these classes so that a user could hypothetically just do something like:

from mylib.models import Class1, Class2, Class3, Class4

without simply moving all these classes into the same file? (Would result in a far too long unreadable unmaintanable file.

Project I'm working on currently accomplishes this by having a names.py file which itself imports everything from everywhere, including statements such as from .somemodule import *, which I have mixed feelings on.

Thoughts, suggestions, etc?


Solution

  • You just need to setup a init file with all the imports that you may need.

    If you could, move all your files/functions to a folder.

    EDIT: Just to clarify that you don't need to move things around, it's just to keep things more organized. In fact, you just need __init__.py in a folder with the imports defined. You can import classes and functions from anywhere into your init, just remember to add them to the __all__ list. Imports example with files from another folder

    Then setup a __init__.py file with all your imports, should like this:

    """
    Module definition...
    
    """
    
    from somefile import Class1, Class2
    from anotherfile import Class3
    from athirdfile import Class4
    
    #If you want some version control, use this to it
    from distutils.version import LooseVersion
    __version__ = "0.0.1"
    __version_info__ = tuple(LooseVersion(__version__).version)
    
    __all__ = [
        "Class1",
        "Class2",
        "Class3",
        "Class4"
    ]
    
    

    Your directory tree should look like this:

    |--mylib/
    |    |--__init__.py
    |    |--somefile.py
    |    |--anotherfile.py
    |    |--athirdfile.py
    |--main.py
    |--...stuff...
    

    Then just call This module where you need it: from mylib import Class1, Class2, Class3, Class4

    Call class from module