Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #95276
| References | <85fv3oj2y6.fsf@benfinney.id.au> |
|---|---|
| Date | 2015-08-12 19:14 +1000 |
| Subject | Re: Ensure unwanted names removed in class definition |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.103.1439370878.3627.python-list@python.org> (permalink) |
On Wed, Aug 12, 2015 at 7:01 PM, Ben Finney <ben+python@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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Ensure unwanted names removed in class definition Chris Angelico <rosuav@gmail.com> - 2015-08-12 19:14 +1000
csiph-web