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

awesoon
  • 32,469
  • 11
  • 74
  • 99
Joost Döbken
  • 3,450
  • 2
  • 35
  • 79

1 Answers1

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)
awesoon
  • 32,469
  • 11
  • 74
  • 99
  • 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)]` – Joost Döbken Apr 12 '16 at 05:50
  • 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 – awesoon Apr 12 '16 at 05:58
  • SQLAlchemy indeed; but within a stand-alone py you think this is not possible? – Joost Döbken Apr 12 '16 at 06:59
  • 1
    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: http://stackoverflow.com/a/5036827/1532460 – awesoon Apr 12 '16 at 13:41
  • Tnx! This works: `globals()['Abc'] = Base`. But how to define the `__mapper_args__` as well? – Joost Döbken Apr 12 '16 at 15:08
  • 1
    Well, you could firstly create all classes using `type` as described in the answer, and then add them into `gloabals()`. – awesoon Apr 12 '16 at 15:10