How Does Cpython Determine Whether A User Supplied An Optional Argument?
I started wondering how CPython can tell the difference between None as a default argument and None as a specified argument. For example, dict.pop() will throw a KeyError if the k
Solution 1:
If the second argument isn't passed, deflt
is a null pointer rather than pointing to None
or any other Python object. This is not something you can do with a function written in Python.
The function you're looking at isn't where the default value is defined. You're looking at an intermediate helper function. The default is specified in an Argument Clinic directive next to dict_pop_impl
:
/*[clinic input]
dict.pop
key: object
default: object = NULL
/
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, default is returned if given, otherwise KeyError is raised
[clinic start generated code]*/
static PyObject *
dict_pop_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
/*[clinic end generated code: output=3abb47b89f24c21c input=eeebec7812190348]*/
{
return _PyDict_Pop((PyObject*)self, key, default_value);
}
See the default: object = NULL
. This comment is preprocessed to generate code that looks at dict.pop
's argument tuple and calls dict_pop_impl
, and the generated code passes a null pointer for default_value
if the argument tuple doesn't contain a value for that argument.
Post a Comment for "How Does Cpython Determine Whether A User Supplied An Optional Argument?"