[Python-Dev] properties and block statement

Josiah Carlson jcarlson at uci.edu
Tue Oct 18 21:56:32 CEST 2005


Antoine Pitrou <solipsis at pitrou.net> wrote:
>>> > What would this mythical block statement look like that would make
> > properties easier to write than the above late-binding or the subclass
> > Property recipe?
>> I suppose something like:
>> class C(object):
> x = prop:
> """ Yay for property x! """
> def __get__(self):
> return self._x
> def __set__(self, value):
> self._x = x
>> and then:
>> def prop(@block):
> return property(
> fget=block.get("__get__"),
> fset=block.get("__set__"),
> fdel=block.get("__delete__"),
> doc=block.get("__doc__", ""),
> )
>> (where "@bargs" would be the syntax to refer to block args as a dict,
> the same way "**kargs" already exist)

You are saving 3 lines over the decorator/function approach at the cost
of possible confusion over blocks and an easily forgotten/not read @
just after an open paren.
Thanks, but I'll stick to the Property decorator, Property subclass,
property late bindings, or even a Property metaclass*, and not need to
modify Python syntax.
 - Josiah
* Property metaclass in an embedded class definition:
class Property(type):
 def __init__(*args):
 pass
 def __new__(cls, name, bases, dct):
 return property(dct.get('get'),
 dct.get('set'),
 dct.get('delete'),
 dct.get('__doc__', ''))
class foo(object):
 class x(object):
 __metaclass__ = Property
 'hello'
 def get(self):
 try:
 return self._x
 except AttributeError:
 self._x = 0
 return 0
 def set(self, value):
 if value >= 5: raise ValueError("value too big")
 self._x = value
 def delete(self):
 del self._x


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /