2

Is it possible to create multiple classes from a list, like this:

for cn in ['ABC', 'DEF', 'GHI']:
    class {cn.capitalize()?}(Base):
        __mapper_args__ = {
            'polymorphic_identity': cn.lower(),
        }

Note: In all questions I found with a similar title, questioners actually wanted to create multiple objects from a single class

1 Answer 1

3

You could create new class at runtime using type:

In [17]: class_names = ['ABC', 'DEF', 'GHI']

In [18]: classes = {name: type(name.capitalize(), (Base,),
                      {'__mapper_args__': {'polymorphic_identity': name.lower()}})
           for name in class_names}

In [19]: classes['DEF']
Out[19]: __main__.Def

In [20]: classes['ABC']().__mapper_args__
Out[20]: {'polymorphic_identity': 'abc'}

In [21]: import inspect

In [22]: inspect.getmro(classes['GHI'])
Out[22]: (__main__.Ghi, __main__.Base, object)
Sign up to request clarification or add additional context in comments.

6 Comments

Ok. The classes are in a dict, but how get them in the system modules? [name for name, obj in inspect.getmembers(sys.modules[__name__]) if inspect.isclass(obj)]
You should describe the main purpose. Are you using SQLAlchemy? Probably, it provides some low-level API that will help you with solving the problem
SQLAlchemy indeed; but within a stand-alone py you think this is not possible?
You could try to place all generated classes into globals() dictionary, although, I don't know if SQLAlchemy be able to use them. See this answer for details: stackoverflow.com/a/5036827/1532460
Well, you could firstly create all classes using type as described in the answer, and then add them into gloabals().
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.