Variadic function: Difference between revisions

Content deleted Content added
Line 48:
{{section-stub}}
 
Python supports very flexible variadic functions. By marking variables with one asterisk (e.g. *var) the given variable is defined to be a tuple of all the extra arguments. By marking variables with two asterisks (e.g. **var) the given variable is a dictionary of all extra [[http://en.wikipedia.org/wiki/Parameter_(computer_science) | keyword arguments]]; the keys are strings, which are the names that were . Conventionally these are called "args" and "kwargs" respectively, but they may be something else, and packages often make good use of this ability to improve readability (e.g. [[BeautifulSoup | http://www.crummy.com/software/BeautifulSoup/documentation.html]]). If they exist, these arguments must be the last one in the list.
Python supports very flexible variadic functions. The param
 
def f(*args, **kwargs):
print args
#args is a [[tuple]] of all the unspecified trailing arguments
print kwargs
#kwargs is a [[dict]] of all the arguments specified using name=val syntax
f(1,2,"cow","kitty")
> (1, 2, "cow", kitty)
> {}
f(arg1=1,sample=2,name="cow",hero="kitty")
> ()
> {"arg1":1, "sample":2, "name":"cow", "hero":"kitty"}
 
f(1,2,name="cow",hero="kitty")
e.g.
> (1, 2)
> {"name":"cow", "hero":"kitty"}
 
f(arg1=1,sample=2,name="cow", "kitty") -> SyntaxError "Non-keyword arg after keyword arg"
 
<!-- this section should go on another page, really... -->
Conversely you may also pass in a tuple or dictionary using the same asterisk-notation and have it automatically expand to fill.
 
def g(a, b, c):
print a, b, c
 
mytuple = 1,2,3
mydict = {"a":"first", "b":"second", "c":"third"}
g(*mytuple) -> 1 2 3
g(**mydict) -> first second third
g(**{"a":"first"}) -> TypeError "g() takes exactly 3 non-keyword arguments (got 1)"
g(**{"a":"first", "b":"second", "c":"third", "d":"fourth"}) -> TypeError "g() got an unexpected keyword argument 'd'"
 
==See also==