Import all classes in directory?

Question:

I found this, but that’s not quite what I want to do.

I want to import all the classes in all the files in a directory. Basically, I want to replace this:

from A import *
from B import *
from C import *

With something dynamic, so that I don’t have keep editing my __init__.py every time I add another file.


The glob solution seems to be the equivalent of

import A
import B
import C

which is not the same at all.

Asked By: mpen

||

Answers:

You can do something like this, although keep in mind isinstance(cls, type) only works with new-style classes.

import os, sys

path = os.path.dirname(os.path.abspath(__file__))

for py in [f[:-3] for f in os.listdir(path) if f.endswith('.py') and f != '__init__.py']:
    mod = __import__('.'.join([__name__, py]), fromlist=[py])
    classes = [getattr(mod, x) for x in dir(mod) if isinstance(getattr(mod, x), type)]
    for cls in classes:
        setattr(sys.modules[__name__], cls.__name__, cls)
Answered By: zeekay

Let’s assume your file structure is as follows:

/Foo
    A.py
    B.py
    C.py

To import all at once, you need to create the __init__.py file in the directory you’d like to import everything from, with following code inside:

__all__ = ['A', 'B', 'C']

This is the file structure after those changes:

/Foo
    A.py
    B.py
    C.py
    __init__.py

Then, you can simply use:

from Foo import *
Answered By: Kamil Marczak

https://julienharbulot.com/python-dynamical-import.html

That is working even with parameters send to the class.

Answered By: tCot
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.