Python Programming, news on the Voidspace Python Projects and all things techie.

Oddity with Iteration and len in Python 2.6 / 3.0

emoticon:envelope This issue was raised by Dino Veihland (core developer of IronPython) when asking whether IronPython should implement a particular behavior of CPython that seemed a bit odd. This in turn was triggered by an IronPython bug report.

Python 3.0 (r30:67503, Dec  6 2008, 21:14:27)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> class X(object):
...     def __iter__(self):
...         return iter([])
...     def __len__(self):
...         print('len called')
...         sys.exit(1)
...
>>> x = X()
>>> list(x)
len called
[]
>>>

(The same thing happens with Python 2.6 but not Python 2.5.)

So you can see that when you create an iterator from an object, __len__ is called - as an optimisation for the interpreter. As it is only called as an optimisation it was implemented in a way that exceptions whilst calling __len__ (or __length_hint__) as a side-effect of creating an iterator won't stop the iterator being created. Even to the extent of ignoring an explicit call to sys.exit()!

Unfortunately that can have the side effect of masking errors in your code - so after a bit of thought Guido has decided that this is a misfeature (a bug) that will be fixed. Another reminder that having multiple implementations is good for a language - design decisions get revisited 'in the cold light of day' as they are reimplemented.

Like this post? Digg it or Del.icio.us it.

Posted by Fuzzyman on 2009-01-15 21:26:15 | |

Categories: , ,


Resolver Systems Featured on the Daily WTF

emoticon:contour Resolver Systems is currently being featured on the front page of The Daily WTF. Thankfully not for the quality of our code, but because Resolver One is advertised there.

Pretty funky ads too:

Like this post? Digg it or Del.icio.us it.

Posted by Fuzzyman on 2009-01-12 10:23:21 | |

Categories: Tags: ,


Hosted by Webfaction

Counter...