Content deleted Content added
StvnLunsford (talk | contribs) |
|||
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.
def f(*args, **kwargs):
print args
print kwargs
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")
> (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==
|