Idiomatic way of specifying default arguments, presence / absence of presence

I often see python code that accepts default arguments and has special behavior when not specified.

If, for example, I want this behavior:

def getwrap(dict, key, default = ??):
    if ???: # default is specified
        return dict.get(key, default)
    else:
        return dict[key]

If I rolled myself, I would get something like:

class Ham:
    __secret = object()
    def Cheese(self, key, default = __secret):
        if default is self.__secret:
            return self.dict.get(key, default)
        else:
            return self.dict[key]

But I do not want to come up with something stupid when there is a standard. What is the idiomatic way to do this in Python?

+3
source share
2 answers

I usually prefer

def getwrap(my_dict, my_key, default=None):
    if default is None:
        return my_dict[my_key]
    else:
        return my_dict.get(my_key, default)

but of course, this assumes that None is never a valid default value.

+6
source

You can do this based on and / or . *args**kwargs

getwrap *args:

def getwrap(my_dict, my_key, *args):
    if args:
        return my_dict.get(my_key, args[0])
    else:
        return my_dict[my_key]

:

>>> a = {'foo': 1}
>>> getwrap(a, 'foo')
1
>>> getwrap(a, 'bar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in getwrap
KeyError: 'bar'
>>> getwrap(a, 'bar', 'Nobody expects the Spanish Inquisition!')
'Nobody expects the Spanish Inquisition!'
+1

Source: https://habr.com/ru/post/1790775/


All Articles