Search code examples
pythonchaining

Using None as parameter to keyword argument


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:

  1. Setting value to some strange object, like a random string
  2. 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


Solution

  • You need to use a sentinel to detect that a default value was not set:

    sentinel = object()
    
    def foo(self, value=sentinel):
        if value is not sentinel:
            print("You passed in something else!")
    

    This works because an instance of object() will always have it's own memory id and thus is will only return True if the exact value was left in place. Any other value will not register as the same object, including None.

    You'll see different variants of the above trick in various different python projects. Any of the following sentinels would also work:

    sentinel = []
    sentinel = {}