I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work?
>>> {}.pop('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented
How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?
Thanks
The convention is often to use arg=None
and use
def foo(arg=None):
if arg is None:
arg = "default value"
# other stuff
# ...
to check if it was passed or not. Allowing the user to pass None
, which would be interpreted as if the argument was not passed.