Python Programming, news on the Voidspace Python Projects and all things techie.
Oddity with Iteration and len in Python 2.6 / 3.0
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.
[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')
>>> x = X()
(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.
Resolver Systems Featured on the Daily WTF
Pretty funky ads too:
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.