Ensure unwanted names removed in class definition
Chris Angelico
rosuav at gmail.com
Wed Aug 12 05:14:30 EDT 2015
On Wed, Aug 12, 2015 at 7:01 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> class Parrot:
> """ A parrot with beautiful plumage. """
>
> plumage = [
> (foo, bar) for (foo, bar) in feathers.items()
> if bar == "beautiful"]
> del foo, bar # ← FAILS, “NameError: name 'foo' is not defined”
>
> How can I write the class definition with the list comprehension and
> *not* keep the incidental names — in code that will run correctly on
> both Python 2 and Python 3?
You could always do explicitly what a Py3 comprehension does, and wrap
it in a function:
plumage = (lambda: [
(foo, bar) for (foo, bar) in feathers.items()
if bar == "beautiful"])()
Hardly clean code, but it will work, and apart from having a redundant
layer of protection in Py3, will do exactly the same thing on both. Is
the lambda nesting cruft worth it?
ChrisA
More information about the Python-list
mailing list