开发者

Idiomatic way of specifying default arguments whose presence/non-presence matter

I often see python code that takes default arguments and has special behaviour when they are not specified.

If I for example want behavior like this:

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

If I were to roll my own, I'd end up with 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 don't want to invent something silly when there certainly is a standard. What is the idiomatic way of doing this in Pyt开发者_StackOverflowhon?


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.


You could do it based on *args and/or **kwargs.

Here's an alternate implementation of getwrap based on *args:

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

And here it is in action:

>>> 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!'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜