1

Is there a better way than the following example to detect if an optional argument has been provided? Even if None is provided, we want to return that instead of raising the exception.

Expected results:

>>> get_value('key-exists-not')  # default not provided
KeyError
>>> get_value('key-exists-not', None)  # should support arg
None
>>> get_value('key-exists-not', default=None)  # as well as kwarg
None
>>> get_value('key-exists-not', default='')
''

Is this the best/recommended way to do it?

def get_value(key, default='somerubbishthatwillneverbeused'):
    try:
        return _data[key]
    except KeyError:
        if default != 'somerubbishthatwillneverbeused':
            return default
        raise
Michael Waterfall
  • 20,497
  • 27
  • 111
  • 168

2 Answers2

6

Use a sentinel value; it's a private singleton that you test agains with is:

_sentinel = object()
def get_value(key, default=_sentinel):
    if default is _sentinel:
         # no other value provided
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

Two options

def foobar (**kwargs):
    if 'some_key' in kwargs:
        # it was provided

And the other

default = object()
def foobar (some_key=default):
    if some_key is default:
        # some_key not specified
Blubber
  • 2,214
  • 1
  • 17
  • 26