generate properties code in class dynamically

JamesEM james.housden at deutsche-boerse.com
Fri May 13 01:45:10 EDT 2011


On May 12, 10:04 pm, Terry Reedy <tjre... at udel.edu> wrote:
> On 5/12/2011 9:11 AM, JamesEM wrote:
>
>
>
> > I would prefer to generate the properties code dynamically from the
> > keys of the dictionaries.
> > What I am looking for is something like:
>
> > class MyClass(object):
>
> >      def __init__(self):
> >          self.d = {}
> >          d['field1'] = 1.0
> >          d['field2'] = 'A'
> >          d['field3'] = [10.0,20.0,30.0]
> >          for f in d:
> >             create_property(f)
>
> > where create_property(f) dynamically creates the property code for
> > field f in MyClass.
>
> > Is this possible?
>
> Without actually trying, I am not sure, but I believe maybe (possibly
> version dependent). The init method is the wrong place. Create the
> properties exactly once, just after the class is created. It is possible
> to add functions to classes as attributes (instance methods) after they
> are created. The property decorators *might* require that they be
> invoked with the class body, I do not know. I would first try with
> property().
>
> Assuming dict name 'd' is fixed:
>
> def gsd(key):
>    def get(self):
>      return self.d[key]
>    def set(self, value):
>      self.d[key] = value
>    def del(self):
>      del self.d[key]
>    return get,set,del
>
> for key in fieldnames:
>    setattr(MyClass, key, property(*gsd(key)))
>
> For recent versions, this could be done within a class decorator, but
> that is only convenient syntactic sugar.
>
> --
> Terry Jan Reedy

Thanks for your help.
I tried the above for get and set which worked as desired. However,
the del did not seem to work for me (using python 2.6.5).
I hope I did not mistype anything, but it objects to def del with a
syntax error. I guess because del is a reserved word.
James



More information about the Python-list mailing list