Import all classes into a directory?

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

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

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

Something dynamic, so I won’t edit my __init__.py every time I add another file.


glob solution seems equivalent

 import A import B import C 

which is not the same.

+8
python
source share
1 answer

You can do something similar, but do not forget that 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) 
+6
source share

All Articles