Thursday, April 3, 2014

Python: passing a mix of keyword arguments and dictionary arguments to a function

So Python is cool because of keyword arguments:

def foo(a=1,b=2,c=3):
  print a,b,c

foo(a=1) # -> 1 2 3

Python is cool because you can pass a dictionary whose keys match the argument names:

def foo(a=1,b=2,c=3):
  print a,b,c

args = {'a': 1, 'b':2}
foo(**args) # -> 1 2 3

But, can you mix the two? Yes, yes you can!

def foo(a=1,b=2,c=3):
  print a,b,c

args = {'a': 1, 'b':2}
foo(c=3, **args) # -> 1 2 3

Hmm, can we screw up the interpreter? What happens if we send the same argument as a keyword AND a dictionary?

def foo(a=1,b=2,c=3):
  print a,b,c

args = {'a': 1, 'b':2}
foo(a=4, **args) # -> TypeError: foo() got multiple values for keyword argument 'a'

Nothing gets past Python, eh?

No comments:

Post a Comment