Dynamic Class Creation in SQLAlchemy

You can dynamically create MyObject using the 3-argument call to type:

type(name, bases, dict)

    Return a new type object. This is essentially a dynamic form of the 
    class statement... 

For example:

mydict={'__tablename__':stored['tablename'],
        '__table_args__':{'autoload':True},}

MyObj=type(stored['objectname'],(Base,),mydict)
print(MyObj)
# <class '__main__.MyObject'>
print(MyObj.__base__)
# <class '__main__.Base'>
print(MyObj.__tablename__)
# my_internal_table_name
print(MyObj.__table_args__)
# {'autoload': True}

Leave a Comment