Ensure unwanted names removed in class definition

Ben Finney ben+python at benfinney.id.au
Thu Aug 13 00:50:52 CEST 2015


Peter Otten <__peter__ at web.de> writes:

> I would probably use a generator expression. These don't leak names:

That's an unexpected inconsistency between list comprehensions versus
generator expressions, then. Is that documented explicitly in the Python
2 documentation?

> Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
> [GCC 4.8.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class Parrot:
> ...     a = [per for per in "abc"]
> ...     b = list(trans for trans in "def")
> ... 
> >>> Parrot.per
> 'c'
> >>> Parrot.trans
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: class Parrot has no attribute 'trans'

We have a winner! That's elegant, expressive, and has the right
behaviour on both Python 2 and Python 3.

-- 
 \         “I turned to speak to God/About the world's despair; But to |
  `\   make bad matters worse/I found God wasn't there.” —Robert Frost |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list