Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does dict.pop() detect if an optional argument has been passed?

Tags:

python

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?

like image 727
math4tots Avatar asked Mar 25 '14 08:03

math4tots


1 Answers

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.

like image 171
Daniel Roseman Avatar answered Sep 30 '22 22:09

Daniel Roseman