Dangerous behavior of list(generator)
Mel
mwilson at the-wire.com
Mon Dec 14 11:09:19 EST 2009
exarkun at twistedmatrix.com wrote:
[ ... ]
it's as if a loop like this:
>
> for a in b:
> c
>
> actually meant this:
>
> for a in b:
> try:
> c
> except StopIteration:
> break
>
> Note, I know *why* the implementation leads to this behavior. I'm
> asking why "the devs" *accept* this.
It's part of the price Python pays for letting people get their hands on the
controls. Consider also:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class dict2(dict):
... def __getitem__ (self, key):
... if key == 'fatal':
... raise KeyError
...
>>> d = dict2()
>>> d['fatal'] = 'Hello, world!'
>>> print d['fatal']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __getitem__
KeyError
>>>
"KeyError when we just put the item into the dict?"
"Yep."
Mel.
>
> Jean-Paul
More information about the Python-list
mailing list