mercredi 21 mai 2014

python - créer une classe dynamique de type DeclarativeMeta dérivé de declarativeBase - Stack Overflow


I want to create dynamic class whose instances are mapped objects that can be used for querying during sqlalchemy


After enough investigation about dynamic classes and carefully going over this post How can I dynamically create derived classes from a base class, so far I have following code:


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,Float
Base = declarative_base()

def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
Base.__init__(self)


newclass = type("DeclarativeMeta", (Base,),{"__init__": __init__,"__tablename__":"vt_person_2009_1","pid":Column(Inte\
ger,primary_key=True)})

SQLAlchemy does not like instance of this class. The reason being mapped classes are of type sqlalchemy.ext.declarative.DeclarativeMeta. The type(newclass()) is of type __main__.DeclarativeMeta.


So question is how do I modify the type of the newclass from main.DeclarativeMeta to sqlalchemy.ext.declarative.DeclarativeMeta


I tried to set the class attribute inside the init function.


self.__class__ = sqlalchemy.ext.declarative.DeclarativeMeta

This time python complained that


TypeError: class assignment: 'DeclarativeMeta' object layout differs from 'DeclarativeMeta'


So far it was fun learning about dynamic classes (and about powers of python).


Thanks for helping.



I want to create dynamic class whose instances are mapped objects that can be used for querying during sqlalchemy


After enough investigation about dynamic classes and carefully going over this post How can I dynamically create derived classes from a base class, so far I have following code:


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,Float
Base = declarative_base()

def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
Base.__init__(self)


newclass = type("DeclarativeMeta", (Base,),{"__init__": __init__,"__tablename__":"vt_person_2009_1","pid":Column(Inte\
ger,primary_key=True)})

SQLAlchemy does not like instance of this class. The reason being mapped classes are of type sqlalchemy.ext.declarative.DeclarativeMeta. The type(newclass()) is of type __main__.DeclarativeMeta.


So question is how do I modify the type of the newclass from main.DeclarativeMeta to sqlalchemy.ext.declarative.DeclarativeMeta


I tried to set the class attribute inside the init function.


self.__class__ = sqlalchemy.ext.declarative.DeclarativeMeta

This time python complained that


TypeError: class assignment: 'DeclarativeMeta' object layout differs from 'DeclarativeMeta'


So far it was fun learning about dynamic classes (and about powers of python).


Thanks for helping.


0 commentaires:

Enregistrer un commentaire