C
Christian Eder
Hi,
I just discovered the following pitfall in Python 2.3.
Consider the following code :
True
So, an "empty" iterator evaluates to True in boolean context.
At a first glance, this is not what one would expect. This causes
several problems, e.g. if you operate on something expected to be
sequence, and you guard your code with "if seq :" to avoid crashing into
an empty sequence, you still crash if you get an empty iterator, even if
the rest of your code is able to deal with an iterator as well as with
any other sequence type.
At a second glance, the behaviour is clear, since the iterator object
does not know wheter it is able to provide the next element, before
having done so.
Anyway, although I don't know how the iterator protocol is implemented
in Python 2.3, I suppose the __nonzero__ could be changed to check
whether a next element can be provided without actually consuming it.
I would like to read some comments on this topic as I'm sure that I'm
not the first one wondering whether the current behaviour should be that
way.
thanks
chris
I just discovered the following pitfall in Python 2.3.
Consider the following code :
True
So, an "empty" iterator evaluates to True in boolean context.
At a first glance, this is not what one would expect. This causes
several problems, e.g. if you operate on something expected to be
sequence, and you guard your code with "if seq :" to avoid crashing into
an empty sequence, you still crash if you get an empty iterator, even if
the rest of your code is able to deal with an iterator as well as with
any other sequence type.
At a second glance, the behaviour is clear, since the iterator object
does not know wheter it is able to provide the next element, before
having done so.
Anyway, although I don't know how the iterator protocol is implemented
in Python 2.3, I suppose the __nonzero__ could be changed to check
whether a next element can be provided without actually consuming it.
I would like to read some comments on this topic as I'm sure that I'm
not the first one wondering whether the current behaviour should be that
way.
thanks
chris