generate properties code in class dynamically

Terry Reedy tjreedy at udel.edu
Thu May 12 16:04:07 EDT 2011


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




More information about the Python-list mailing list