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.

a dictionary becomes a more general multiway branching tool than what I couldshow you in Chapter 12’s coverage of if statements.To make this work without lambda, you’d need to instead code three def statementssomewhere else in your file, outside the dictionary in which the functions are to beused:def f1( ): return 2 + 2def f2( ): return 2 * 4def f3( ): return 2 ** 6...key = 'one'{'already': f1, 'got': f2, 'one': f3}[key]( )This works, too, but your defs may be arbitrarily far away in your file, even if theyare just little bits of code. The code proximity that lambdas provide is especially usefulfor functions that will only be used in a single context—if the three functions hereare not useful anywhere else, it makes sense to embed their definitions within thedictionary as lambdas. Moreover, the def form requires you to make up names forthese little functions that may clash with other names in this file.lambdas also come in handy in function argument lists as a way to inline temporaryfunction definitions not used anywhere else in your program; we’ll see some examplesof such other uses later in this chapter, when we study map.How (Not) to Obfuscate Your <strong>Python</strong> CodeThe fact that the body of a lambda has to be a single expression (not a series of statements)would seem to place severe limits on how much logic you can pack into alambda. If you know what you’re doing, though, you can code most statements in<strong>Python</strong> as expression-based equivalents.For example, if you want to print from the body of a lambda function, simply saysys.stdout.write(str(x)+'\n’), instead of print x (recall from Chapter 11 that thisis what print really does). Similarly, to nest logic in a lambda, you can use the if/elseternary expression introduced in Chapter 13, or the equivalent but trickier and/orcombination also described there. As you learned earlier, the following statement:if a:belse:ccan be emulated by either of these roughly equivalent expressions:b if a else c((a and b) or c)Anonymous Functions: lambda | 347

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

Saved successfully!

Ooh no, something went wrong!