Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 952
Jake Avatar asked Nov 01 '08 02:11

Jake


2 Answers

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.

like image 196
Markus Jarderot Avatar answered Oct 03 '22 01:10

Markus Jarderot


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.

like image 24
ddaa Avatar answered Oct 03 '22 01:10

ddaa