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.
I guess you mean "keyword argument", when you say "named parameter". dict.pop()
does not accept keyword argument, so this part of the question is moot.
>>> {}.pop('test', d=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop() takes no keyword arguments
That said, the way to detect whether an argument was provided is to use the *args
or **kwargs
syntax. For example:
def foo(first, *rest):
if len(rest) > 1:
raise TypeError("foo() expected at most 2 arguments, got %d"
% (len(rest) + 1))
print 'first =', first
if rest:
print 'second =', rest[0]
With some work, and using the **kwargs
syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error.
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