12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

act = knights( )>>> act('robin')'Sir robin'In this example, prior to Release 2.2, the value for the name title would typicallyhave been passed in as a default argument value instead; flip back to the scopes coveragein Chapter 16 if you’ve forgotten why.Why Use lambda?Generally speaking, lambdas come in handy as a sort of function shorthand thatallows you to embed a function’s definition within the code that uses it. They areentirely optional (you can always use defs instead), but they tend to be simpler codingconstructs in scenarios where you just need to embed small bits of executablecode.For instance, we’ll see later that callback handlers are frequently coded as inlinelambda expressions embedded directly in a registration call’s arguments list, insteadof being defined with a def elsewhere in a file, and referenced by name (see the sidebar“Why You Will Care: Callbacks” later in this chapter for an example).lambdas are also commonly used to code jump tables, which are lists or dictionaries ofactions to be performed on demand. For example:L = [(lambda x: x**2), (lambda x: x**3), (lambda x: x**4)]for f in L:print f(2) # Prints 4, 8, 16print L[0](3) # Prints 9The lambda expression is most useful as a shorthand for def, when you need to stuffsmall pieces of executable code into places where statements are illegal syntactically.This code snippet, for example, builds up a list of three functions by embeddinglambda expressions inside a list literal; a def won’t work inside a list literal like thisbecause it is a statement, not an expression.You can do the same sort of thing with dictionaries and other data structures in<strong>Python</strong> to build up action tables:>>> key = 'got'>>> {'already': (lambda: 2 + 2),... 'got': (lambda: 2 * 4),... 'one': (lambda: 2 ** 6)... }[key]( )8Here, when <strong>Python</strong> makes the dictionary, each of the nested lambdas generates andleaves behind a function to be called later; indexing by key fetches one of those functions,and parentheses force the fetched function to be called. When coded this way,346 | Chapter 17: Advanced Function Topics

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

Saved successfully!

Ooh no, something went wrong!