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.

around this, simply build up the arguments list with tuple operations, and call thefunction indirectly through apply:>>> args = (2,3) + (4,)>>> args(2, 3, 4)>>> apply(func, args)9Passing keyword argumentsThe apply call also supports an optional third argument, where you can pass in a dictionarythat represents keyword arguments to be passed to the function:>>> def echo(*args, **kwargs): print args, kwargs...>>> echo(1, 2, a=3, b=4)(1, 2) {'a': 3, 'b': 4}This allows you to construct both positional and keyword arguments at runtime:>>> pargs = (1, 2)>>> kargs = {'a':3, 'b':4}>>> apply(echo, pargs, kargs)(1, 2) {'a': 3, 'b': 4}apply-Like Call Syntax<strong>Python</strong> also allows you to accomplish the same effect as an apply call with specialsyntax in the call. This syntax mirrors the arbitrary arguments syntax in def headersthat we met in Chapter 16. For example, assuming the names in this example are stillas assigned earlier:>>> apply(func, args) # Traditional: tuple9>>> func(*args) # New apply-like syntax9>>> echo(*pargs, **kargs) # Keyword dictionaries too(1, 2) {'a': 3, 'b': 4}This special call syntax is newer than the apply function, and is generally preferredtoday. It doesn’t have any obvious advantages over an explicit apply call, apart fromits symmetry with def headers, and requiring a few less keystrokes. However, thenew call syntax alternative also allows us to pass along real additional arguments,and so is more general:>>> echo(0, *pargs, **kargs) # Normal, *tuple, **dictionary(0, 1, 2) {'a': 3, 'b': 4}Applying Functions to Arguments | 351

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

Saved successfully!

Ooh no, something went wrong!