Possible Duplicate:
python – returning a default value
I have a function in a class:
def foo(self, value = None):
if value is None:
return self.value
self.value = value
return self
This is a getter and setter combined into one, with the advantage that I can chain functions like this:
three = anInstanceOfMyClass.foo(3).bar().foo()
The problem appears when I do like this:
shouldBeNoneButIsThree = anInstanceOfMyClass.foo(3).foo(None).foo()
Here foo thinks that I did not pass an argument.
I can avoid this by:
- Setting value to some strange object, like a random string
- Create an object instance in the constructor which value has as default value
Both seem a bit too much work, what is an easier way?
setting value to something
You need to use a sentinel to detect that a default value was not set:
This works because an instance of
object()will always have it’s own memory id and thusiswill only return True if the exact value was left in place. Any other value will not register as the same object, includingNone.You’ll see different variants of the above trick in various different python projects. Any of the following sentinels would also work: