Search code examples
pythonpython-3.ximportpython-importimporterror

How to import multiple objects in different files easily


application
├── folder
│       └── A.py --> class A:...
│       └── B.py --> class B:...  
│       └── C.py --> class C:...
└── __init.py__

What is the best way to get classes A, B and C into __init__.py? Below is one way to do it

from .folder.A import A
from .folder.B import B
from .folder.C import C

But is there a simpler one liner I could be using? something like from .folder.* import A,B,C


Solution

  • What you wrote would do it and there's no multi-module import one-liner unless you want to write a loop:

    import importlib
    for sub in "A B C".split():
        globals()[sub] = getattr(importlib.import_module(".folder." + sub), sub)
    

    I only wrote the above to show how unsightly this is.

    Slightly better method is to do it in folder.__init__

    # folder.__init__
    from A import *
    from B import *
    from C import *
    
    # __init__
    from .folder import *
    

    To retain some control of this and prevent surprises, define __all__ in individual modules to limit what's being pulled to the top:

    # folder.A
    __all__ = ["A"]
    
    # folder.B
    __all__ = ["B"]
    
    # etc.
    

    Now, what I'd really recommend here is this: don't break things up into modules until you find a reason for it. If there's such a tight dependency between A/B/C that they always end up imported together -- which will be the case for your question -- put them all into a folder.py module (not even separate directory) and just do from .folder import A, B, C in the __init__. The reason for modules to exist is to loosen dependencies between code blocks and allow some of the code to be used without importing more. If some code must always be together, keep it in the same module.