I am trying to create a series of types using type(name, bases, attributes)
without explicitly assigning those types to variables, and then make them available for import from other classes.
What I have so far is something like this
src/
__init__.py
a/
__init__.py
a_module.py
b/
__init__.py
b_module.py
In src/a/__init__.py
I have
import inspect
import sys
for c in inspect.getmembers(sys.modules['src.a.a_module'], inspect.isclass):
type(f'{c.__name__}New, (object,), {})
Then I would like to import the type defined above in src/b/b_module.py
like
from src.a import AClassNew
a = AClassNew()
but this of course gives an ImportError: cannot import name
AClassNew`.
I realize I can put
AClassNew = type('AClassNew', (object,), {})
in src/a/__init__.py
and everything will work, but I'd like to do this for any classes defined in src/a/a_module.py
without defining them explicitly.
Is there a way to get this (or something similar) to work?
I got this working by just updating
globals()
insrc/a/__init__.py
.This adds the type with the correct name to the classes of this module and makes it available for import from other modules.