The Python Oracle

Dynamic Class Creation in SQLAlchemy

This video explains
Dynamic Class Creation in SQLAlchemy

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs

--

Chapters
00:00 Question
01:20 Accepted answer (Score 33)
01:52 Thank you

--

Full question
https://stackoverflow.com/questions/2768...

Accepted answer links:
[3-argument call to ]: http://docs.python.org/library/functions...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sqlalchemy #metaprogramming #metaclass #declarative

#avk47



ACCEPTED ANSWER

Score 35


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}