[Python-Dev] Declaring setters with getters (original) (raw)
Guido van Rossum guido at python.org
Sat Nov 10 07:00:55 CET 2007
- Previous message: [Python-Dev] Only one week left for PyCon proposals!
- Next message: [Python-Dev] Declaring setters with getters
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
To follow up, I now have a patch. It's pretty straightforward.
This implements the kind of syntax that I believe won over most folks in the end:
@property def foo(self): ...
@foo.setter def foo(self, value=None): ...
There are also .getter and .deleter descriptors. This includes the hack that if you specify a setter but no deleter, the setter is called without a value argument when attempting to delete something. If the setter isn't ready for this, a TypeError will be raised, pretty much just as if no deleter was provided (just with a somewhat worse error message :-).
I intend to check this into 2.6 and 3.0 unless there is a huge cry of dismay. Docs will be left to volunteers as always.
--Guido
On Oct 31, 2007 9:08 AM, Guido van Rossum <guido at python.org> wrote:
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/)
-- --Guido van Rossum (home page: http://www.python.org/~guido/)
- Previous message: [Python-Dev] Only one week left for PyCon proposals!
- Next message: [Python-Dev] Declaring setters with getters
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]