Automatic Attribute Assignment during Class Inheritance

gizli mehmetf at gmail.com
Wed Sep 9 23:14:33 EDT 2009


Hi all,

I have been trying to do a programming trick with python and so far I
failed. I am using sqlalchemy in my code and writing a framework with
it. This framework uses something called polymorphic identity
attribute to define the do single table inheritance. Here's roughly
how it works:

1. Define a base ORM class in SQLAlchemy:
class Task:
     ....some params..
     __mapper_args__ = dict(polymorphic_on = type)

2. Anyone who wants to extend this Task class would have to do this:
class MyTask(Task):
     __mapper_args__ = dict(polymorphic_identity = 'MyTask')

I do not want to force the consumers of this framework to write this
obscure line of code. I was wondering if it is possible (at class
definition time) to capture the fact that MyTask extends Task and
automatically insert the polymorphic_identity key into the
__mapper_args__ class attribute (with value set to __name__).

So far, I have not been able to do anything because during class
definition time, there is no a lot of variables I can access. *self*
obviously does not work. __name__ and __class__ are also useless.

I am thinking, it could be possible if I could write a class wrapper.
I.e. the consumers would extend a wrapper instead of Task class. This
wrapper would return a class object with the __mapper_args__. I could
not find any examples on this topic.

I would really appreciate your help.



More information about the Python-list mailing list