[Python-Dev] Declaring setters with getters
Guido van Rossum
guido at python.org
Wed Oct 31 18:08:03 CET 2007
I've come up with a relatively unobtrusive pattern for defining
setters. Given the following definition:
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.__get__, func, func, prop.__doc__)
return helper
we can declare getters and setters as follows:
class C(object):
_encoding = None
@property
def encoding(self):
return self._encoding
@propset(encoding)
def encoding(self, value=None):
if value is not None:
unicode("0", value) # Test it
self._encoding = value
c = C()
print(c.encoding)
c.encoding = "ascii"
print(c.encoding)
try:
c.encoding = "invalid" # Fails
except:
pass
print(c.encoding)
I'd like to make this a standard built-in, in the hope the debate on
how to declare settable properties.
I'd also like to change property so that the doc string defaults to
the doc string of the getter.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list