You are here
Python property gotcha
Liraz Siri - Tue, 2011/06/14 - 11:14 -
6 comments
If you like using a single getter/setter function for your properties, watch out if using None for the default. If you do that you won't be able to set your property to None!
Example code and workaround...
class CantSetNone(object):
def __init__(self):
self._test = None
def test(self, val=None):
print "test(%s)" % `val`
if val is None:
return self._test
else:
self._test = val
test = property(test, test)
class UNDEFINED:
pass
class CanSetNone(object):
def __init__(self):
self._test = None
def test(self, val=UNDEFINED):
print "test(%s)" % `val`
if val is UNDEFINED:
return self._test
else:
self._test = val
test = property(test, test)
Comments
the shorter version
The shorter version of sentinel declaration is
UNDEFINED = object()
But why?
Just so that I understand, what is the point in this example of having the get and set in the same method?
For languages which don't have properties I can understand (ie in javascript jQuery has val() and val(someStuff as methods on inputfields), but just I can't see the need in Python since properties serve the same purpose.
re: Python property gotcha
This is the first idea that came to me. YMMV.
Simpler solution
Given your implementation, this is simpler:
If you are going to do something besides setting and getting in your setter and getter, then this is more explicit and avoids the problem:
Sorry, but this has little to
Sorry, but this has little to do with properties but with choosing right sentinels in default arguments.
WE WANT Undefined!!
WE WANT Undefined!!
Pages
Add new comment