creating many similar properties

Carl Banks pavlovevidence at gmail.com
Wed Oct 18 04:27:37 EDT 2006


George Sakkis wrote:
> Michele Simionato wrote:
> > import sys
> >
> > def defprop(name, default=127):
> >     loc = sys._getframe(1).f_locals
> >     prop = '_%s' % name
> >     def _set(self, v):
> >         v_new = v % 256
> >         setattr(self, prop, v_new)
> >     def _get(self):
> >         return getattr(self, prop, default)
> >     loc[name] = property(_get, _set)
> >
> > class RC(object):
> >     defprop('pwm01')
> >     defprop('pwm02')
> >
> > rc = RC()
> >
> > print rc.pwm01 # 127
> > print rc.pwm02 # 127
> > rc.pwm02 = 1312
> > print rc.pwm02 # 32
> >
> > This is a bit hackish, but I would prefer this over a metaclass
> > solution. since it does not add
> > any hidden magic to your class.
>
> Why is this less hidden or magical than a metaclass ?

Devil's Advocate: he did say "hidden magic TO YOUR CLASS".

If you use a (real) metaclass, then you have the icky feeling of a
class permanently tainted by the unclean metaclass (even though the
metaclass does nothing other than touch the class dict upon creation);
whereas if you use Michele Simionato's hack, the icky feeling of using
a stack frame object goes away after the property is created: you are
left with a clean untainted class.

Personally, the former doesn't make me feel icky at all.


Carl Banks




More information about the Python-list mailing list