12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Collecting argumentsThe first use, in the function definition, collects unmatched positional argumentsinto a tuple:>>> def f(*args): print args...When this function is called, <strong>Python</strong> collects all the positional arguments into a newtuple, and assigns the variable args to that tuple. Because it is a normal tuple object,it can be indexed, stepped through with a for loop, and so on:>>> f( )()>>> f(1)(1,)>>> f(1,2,3,4)(1, 2, 3, 4)The ** feature is similar, but it only works for keyword arguments—it collects theminto a new dictionary, which can then be processed with normal dictionary tools. Ina sense, the ** form allows you to convert from keywords to dictionaries, which youcan then step through with keys calls, dictionary iterators, and the like:>>> def f(**args): print args...>>> f( ){ }>>> f(a=1, b=2){'a': 1, 'b': 2}Finally, function headers can combine normal arguments, the *, and the ** to implementwildly flexible call signatures:>>> def f(a, *pargs, **kargs): print a, pargs, kargs...>>> f(1, 2, 3, x=1, y=2)1 (2, 3) {'y': 2, 'x': 1}In fact, these features can be combined in even more complex ways that may seemambiguous at first glance—an idea we will revisit later in this chapter. First, though,let’s see what happens when * and ** are coded in function calls instead of definitions.Unpacking argumentsIn recent <strong>Python</strong> releases, we can use the * syntax when we call a function, too. Inthis context, its meaning is the inverse of its meaning in the function definition—itunpacks a collection of arguments, rather than building a collection of arguments.For example, we can pass four arguments to a function in a tuple, and let <strong>Python</strong>unpack them into individual arguments:>>> def func(a, b, c, d): print a, b, c, d...>>> args = (1, 2)>>> args += (3, 4)334 | Chapter 16: Scopes and Arguments

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!