Search code examples
pythondefault-valuenamed-parameters

Determine if a named parameter was passed


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


Solution

  • 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.