Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5254

Re: generate properties code in class dynamically

From Terry Reedy <tjreedy@udel.edu>
Subject Re: generate properties code in class dynamically
Date 2011-05-12 16:04 -0400
References <f5a65253-def8-41c8-b722-97cd76bc72d0@32g2000vbe.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1489.1305230663.9059.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

generate properties code in class dynamically JamesEM <james.housden@deutsche-boerse.com> - 2011-05-12 06:11 -0700
  Re: generate properties code in class dynamically nn <pruebauno@latinmail.com> - 2011-05-12 07:14 -0700
  Re: generate properties code in class dynamically Terry Reedy <tjreedy@udel.edu> - 2011-05-12 16:04 -0400
    Re: generate properties code in class dynamically JamesEM <james.housden@deutsche-boerse.com> - 2011-05-12 22:45 -0700

csiph-web