How can I create a bunch of types and make them av

2019-07-29 13:21发布

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 nameAClassNew`.

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?

1条回答
爷的心禁止访问
2楼-- · 2019-07-29 13:44

I got this working by just updating globals() in src/a/__init__.py.

for c in inspect.getmembers(sys.modules['src.a.a_module'], inspect.isclass):
    new_class_name = f'{c.__name__}New'
    new_class = type(new_class_name, (object,), {})
    globals[new_class_name] = new_class

This adds the type with the correct name to the classes of this module and makes it available for import from other modules.

查看更多
登录 后发表回答