creating many similar properties

Michele Simionato michele.simionato at gmail.com
Wed Oct 18 04:27:22 EDT 2006


George Sakkis wrote:
>
> from itertools import chain, izip, repeat
>
> def ByteProperties(*names, **defaulted_names):
>     def byte_property(name, default):
>         return property(lambda self: getattr(self, name, default),
>                         lambda self,v: setattr(self, name, v%256))
>     def make_class(clsname, bases, dict):
>         for name,default in chain(izip(names, repeat(127)),
>                                   defaulted_names.iteritems()):
>             assert name not in dict # sanity check
>             dict[name] = byte_property('_'+name, default)
>         return type(clsname,bases,dict)
>     return make_class
>
>
> class RC(object):
>     __metaclass__ = ByteProperties('pwm01', pwm02=64)

Notice that you are NOT using a custom metaclass here, you are just
using the metaclass hook
and you will avoid all issues of custom metaclasses. This is exactly
the approach I advocate
in the paper I referred before, so I think your solution is pretty safe
in that respect. Still I
think in this particular problem avoiding the __metaclass__ at all is
possible and it should be
preferred, just for sake of simplicity, not of safety).

 Michele Simionato

  M




More information about the Python-list mailing list