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.

Because expressions like these can be placed inside a lambda, they may be used toimplement selection logic within a lambda function:>>> lower = (lambda x, y: x if x < y else y)>>> lower('bb', 'aa')'aa'>>> lower('aa', 'bb')'aa'Furthermore, if you need to perform loops within a lambda, you can also embedthings like map calls and list comprehension expressions (tools we met earlier, inChapter 13, and will revisit later in this chapter):>>> import sys>>> showall = (lambda x: map(sys.stdout.write, x))>>> t = showall(['spam\n', 'toast\n', 'eggs\n'])spamtoasteggs>>> showall = lambda x: [sys.stdout.write(line) for line in x]>>> t = showall(('bright\n', 'side\n', 'of\n', 'life\n'))brightsideoflifeNow that I’ve shown you these tricks, I am required by law to ask you to please onlyuse them as a last resort. Without due care, they can lead to unreadable (a.k.a. obfuscated)<strong>Python</strong> code. In general, simple is better than complex, explicit is better thanimplicit, and full statements are better than arcane expressions. On the other hand,you may find these techniques useful in moderation.Nested lambdas and Scopeslambdas are the main beneficiaries of nested function scope lookup (the E in theLEGB rule we met in Chapter 16). In the following, for example, the lambda appearsinside a def—the typical case—and so can access the value that the name x had inthe enclosing function’s scope at the time that the enclosing function was called:>>> def action(x):... return (lambda y: x + y) # Make and return function, remember x...>>> act = action(99)>>> act>>> act(2)101348 | Chapter 17: Advanced Function Topics

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

Saved successfully!

Ooh no, something went wrong!