d = dict()
d.pop('hello', None) # No exception thrown
d.pop('hello', 0) # No exception thrown
d.pop('hello') # KeyError
I had thought that in Python we usually tested whether a default argument was passed by testing the argument with some sort of default value.
I can't think of any other 'natural' default value that dict.pop
would have used.
Is dict.pop
using some other means to test for the optional argument? Or is it using some more esoteric default value?
Well, dict
is implemented in C, so Python semantics don't really apply. Otherwise, I'd say look at the source in any case.
However, a good pattern for this is to use a sentinel as the default value. That will never match against anything passed in, so you can be sure that if you get that value, you only have one argument.
sentinel = object()
def get(value, default=sentinel):
if default is sentinel:
# etc
This is an appropriate use of is
, as you want to be sure you're checking for the exact sentinel object, not just something that evaluates equal to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With