I have an abstract base class with a number of derived classes. I'm trying to achieve the same behaviour that I would get by placing all the derived classes in the same file as the base class, i.e. if my classes are Base
, DerivedA
, DerivedB
, DerivedC
in the file myclass.py
I can write in another file
import myclass
a = myclass.DerivedA()
b = myclass.DerivedB()
c = myclass.DerivedC()
but with each derived class in its own file. This has to be dynamic, i.e. such that I could e.g. delete derived_c.py
and everything still works except that now I can no longer call myclass.DerivedC
, or that if I add a derived_d.py
, I could use it without touching the __init__.py
so simply using from derived_c import DerivedC
is not an option.
I've tried placing them all in a subdirectory and in that directory's __init__.py
use pkgutil.walk_packages()
to import all the files dynamically, but I can't get them to then be directly in the module's namespace, i.e. rather than myclass.DerivedC()
I have to call myclass.derived_c.DerivedC()
because I can't figure out how (or if it's possible) to use importlib to achieve the equivalent of a from xyz import *
statement.
Any suggestions for how I could achieve this? Thanks!
Edit: The solutions for Dynamic module import in Python don't provide a method for automatically importing the classes in all modules into the namespace of the package.