0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks RScop! It may take me a bit to process this and test it out in the context of the project I'm working on. Will follow up at some point, just to avoid pre-maturely marking as accepted answer - but this looks promising!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.