Is there a good reason why when you try to take an element from an
already exausted iterator, it throws StopIteration instead of some other
exception ? I've lost quite some times already because I was using a lot
of iterators and I forgot that that specific function parameter was one.
Exemple : def f(i):
.... print list(i)
.... print list(i)
.... f(iter(range(2) ))
[0, 1]
[]
This is using Python 2.4.2
May 17 '06
21 1413
Fredrik Lundh a écrit : Christophe wrote:
Because I'm still waiting for a valid answer to my question. The answer "Because it has been coded like that" or is not a valid one.
it's been coded like that because that's what the specification says:
http://www.python.org/dev/peps/pep-0234/
I didn't though I had to mention that "Because the spec has been writen like that" wasn't a valid answer either.
so what is a valid answer?
Some valid use case for that behaviour, some example of why what I ask
could cause problems, some implementation difficulties etc ...
Saying it's like that because someone said so isn't exactly what I was
expecting as an answer :) People sometimes can be wrong you know.
Fredrik Lundh schreef: Christophe wrote:
Because I'm still waiting for a valid answer to my question. The answer "Because it has been coded like that" or is not a valid one. it's been coded like that because that's what the specification says:
http://www.python.org/dev/peps/pep-0234/ I didn't though I had to mention that "Because the spec has been writen like that" wasn't a valid answer either.
so what is a valid answer?
I think he wants to know why the spec has been written that way.
The rationale mentions exhausted iterators:
"Once a particular iterator object has raised StopIteration, will
it also raise StopIteration on all subsequent next() calls?
Some say that it would be useful to require this, others say
that it is useful to leave this open to individual iterators.
Note that this may require an additional state bit for some
iterator implementations (e.g. function-wrapping iterators).
Resolution: once StopIteration is raised, calling it.next()
continues to raise StopIteration."
This doesn't, however, completey answer the OP's question, I think. It
is about raising or not raising StopIteration on subsequent next() calls
but doesn't say anything on possible alternatives, such as raising
another exception (I believe that's what the OP would like).
Not that I know of use cases for other exceptions after StopIteration;
just clarifying what I think the OP means.
--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton
Roel Schroeven
Diez B. Roggisch a écrit : Christophe wrote:
Fredrik Lundh a écrit :
Christophe wrote:
Because I'm still waiting for a valid answer to my question. The answer "Because it has been coded like that" or is not a valid one.
it's been coded like that because that's what the specification says:
http://www.python.org/dev/peps/pep-0234/ I didn't though I had to mention that "Because the spec has been writen like that" wasn't a valid answer either.
The important thing is: it _is_ specified. And what about code like this:
iterable = produce_some_it erable()
for item in iterable: if some_condition( item) break do_something()
for item in iterable: do_something_wi th_the_rest()
If it weren't for StopIteration raised if the iterable was exhausted, you'd have to clutter that code with something like
try: for item in iterable: do_something_wi th_the_rest() except IteratorExhaust ed: pass
It would be ugly but you could do that instead :
iterable = produce_some_it erable()
for item in iterable:
if some_condition( item)
break
do_something()
else:
iterable = []
for item in iterable:
do_something_wi th_the_rest()
I'll admit that the else clause in for/while loops isn't the most common
and so some people might be a little troubled by that.
There's also that :
iterable = produce_some_it erable()
for item in iterable:
if some_condition( item)
for item in iterable:
do_something_wi th_the_rest()
break
do_something()
What makes you say that this is better than the above? Just because _you_ had some cornercases that others seems not to have (at least that frequently, I personally can't remember I've ever bitten by it) isn't a valid reason to _not_ do it as python does.
Maybe I've used more iterables than most of you. Maybe I've been doing
that wrong. But I'd like to think that if I've made those mistakes,
others will make it too and would benefit for some help in debugging
that from the interpreter :)
Besides that: it would be a major change of semantics of iterators that I seriously doubt it would make it into anything before P3K. So - somewhat a moot point to discuss here I'd say.
It wouldn't be such a big semantic change I think. You could add that
easily[1] as deprecation warning at first and later on switch to a full
blown error.
[1] "Easily" provided you can easily code what I ask itself ;)
Roel Schroeven a écrit : Fredrik Lundh schreef: so what is a valid answer?
I think he wants to know why the spec has been written that way.
The rationale mentions exhausted iterators:
"Once a particular iterator object has raised StopIteration, will it also raise StopIteration on all subsequent next() calls? Some say that it would be useful to require this, others say that it is useful to leave this open to individual iterators. Note that this may require an additional state bit for some iterator implementations (e.g. function-wrapping iterators).
Resolution: once StopIteration is raised, calling it.next() continues to raise StopIteration."
This doesn't, however, completey answer the OP's question, I think. It is about raising or not raising StopIteration on subsequent next() calls but doesn't say anything on possible alternatives, such as raising another exception (I believe that's what the OP would like).
Exactly !
Not that I know of use cases for other exceptions after StopIteration; just clarifying what I think the OP means.
There are no use cases yet for me. I want those exceptions as an hard
error for debuging purposes.
Christophe wrote: Maybe I've used more iterables than most of you. Maybe I've been doing that wrong.
your problem is that you're confusing iterables with sequences. they're
two different things.
</F>
Fredrik Lundh a écrit : Christophe wrote:
Maybe I've used more iterables than most of you. Maybe I've been doing that wrong.
your problem is that you're confusing iterables with sequences. they're two different things.
Yes, I know perfectly well that the bugs were my fault. But this doesn't
prevent me from asking for a feature that will have ( in my opinion ) a
negligible effect of current valid code and will help all of us catch
errors earlier.
Christophe wrote: Yes, I know perfectly well that the bugs were my fault. But this doesn't prevent me from asking for a feature that will have ( in my opinion ) a negligible effect of current valid code and will help all of us catch errors earlier.
.... and apparently choosing to ask in such a way that guarantees
practically no one will take your suggestion seriously.
--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Chance favors the trained mind.
-- Louis Pasteur
"Christophe " <ch************ *@free.fr> wrote in message
news:44******** **************@ news.free.fr... Instead of saying that all works as intended could you be a little helpful and tell me why it was intended in such an obviously broken way instead ?
I answered both your explicit and implied questions in good faith. But you
seem to be too attached to your pre-judgment to have benefited much, so I
won't waste my time and yours saying more. Instead I suggest that you try
this:
1. Write a specification for your an alternate, more complicated, iterator
protocol.
2. Write a simple class with .next method that implements your
specification.
3. Test your class with your example.
4. Consider how you would persuade people to add the extra machinery
needed.
5. Consider what you would do when people don't.
If you want, post a report on your experiment, and I will read it if I see
it.
Terry Jan Reedy
Terry Reedy a écrit : "Christophe " <ch************ *@free.fr> wrote in message news:44******** **************@ news.free.fr...
Instead of saying that all works as intended could you be a little helpful and tell me why it was intended in such an obviously broken way instead ?
I answered both your explicit and implied questions in good faith. But you seem to be too attached to your pre-judgment to have benefited much, so I won't waste my time and yours saying more. Instead I suggest that you try this:
1. Write a specification for your an alternate, more complicated, iterator protocol.
Specification : same as now except iterators raise once StopIteration
and any subsequent call to next raises ExaustedIterato rError.
2. Write a simple class with .next method that implements your specification.
class ExaustedIterato rError(Exceptio n):
pass
class safe_iter(objec t):
def __init__(self, seq):
self.it = iter(seq)
def __iter__(self):
return self
def next(self):
try:
return self.it.next()
except StopIteration:
del self.it
raise
except AttributeError:
raise ExaustedIterato rError
3. Test your class with your example.
it = safe_iter(range (10)) print list(it)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print list(it)
Traceback (most recent call last):
File "safe_iter_test .py", line 20, in ?
print list(it)
File "safe_iter_test .py", line 13, in next
raise ExaustedIterato rError
__main__.Exaust edIteratorError
4. Consider how you would persuade people to add the extra machinery needed.
Well, the main reason for such change is and will always be to catch
bugs. The fact is, using duct typing is something very common with the
Python language. And as such, considering a lot of functions which take
sequences as parameters work as well with an iterator instead, you can
say that it's an application of duct typing.
The problem is of course the same as for cases. Even if those two objets
( iterator and container ) look alike from a certain point of view, they
have some fundamental differences.
So, we have quite a few functions which take freely either a container
or an iterator, until someone changes that function a little. At that
point there are three kind errors which happen :
- the function expected a sequence and tries to access it's [] operator
which fails. Standard duct typing behaviour.
- the function uses the iterator more than once and so, sometimes it
works without errors but produces an incorrect result.
- the function uses the iterator more than once but never exhausts it's
values. Same result as above but much harder to catch.
In the sake of avoiding behaviour which lets obvious errors pass and
produces incorrect results, I propose to change the standard behaviour
of all the iterators in the standard Python. The change will be so that
they refuse to be used anymore once they have been exausted. Thus it'll
help catch the second class. The other procedure used to catch such bugs
would require explicit typing of the function parameters but this is for
some other proposal.
5. Consider what you would do when people don't.
I'm already doing it. Cleaning up the code, changing parameters names
around so that it is clear such parameter is an iterator and that other
one is not, making some functions explicitly refuse iterators etc ... It
should not that that last feature will be useful even without the
exhausted iterator guard I propose.
If you want, post a report on your experiment, and I will read it if I see it.
I suppose I could add safe_iter to the builtins in my project and use it
around. It would be easy to catch all usages of that one once we settle
on something different then.
Consider this example: X = range(5) Y = iter(X) Z = iter(Y)
As you can see, X is a container, and Y is an iterator.
They are simliar in that "iter" works on them both.
Cristoph claims that this causes confusion.
Why? Because "iter" doesn't have the same meaning for both of them.
For X it always returns an iterator that yields the same set of values.
For Y it returns an iterator yielding different values each time.
Z = iter(Y) Z.next()
0 Z = iter(Y) Z.next()
1
Most of the uses of iterators iterate all values until exaustion.
Given that, the first call to "iter" will mean the same for an iterator
and a container, but the second one won't.
Allow me to compare it to division in python 2.4 4./2, 4/2
2.0, 2 5./2, 5/2
2.5, 2
Division sometimes works the same for integers and reals, and sometimes
doesn't.
This caused consfusion and bugs, and that's why future Pythons will
change that.
But changing "iter" to have the same meaning for containers and
iterables is impossible.
You cannot, conceptually, reiterate an iterator.
So what Cristoph is suggesting - is to add an exception for the cases
in which iterators and collections behave differently.
Somewhat similar to this:
4/2
2 5/2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IntegerDivision Error: 5 does not divide by 2 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ray Gardener |
last post by:
I was wondering if anyone had tried implementing fuzzy logic set
concepts in C++, because in FL, the concept of "type" or "class"
is fuzzy; things belong (or are of) a given type only by degree.
e.g., in a hypothetical fuzzy C++ language one could say:
class pickle : public vegetable 0.2
{
// pickle is not so much a vegetable as, say, onion is.
};
|
by: deancoo |
last post by:
If I have a container, say a vector, with 5 elements, and I initialize
iterator variables to point to the beginning and end of the container, are
those iterators going to always be valid if I replace the elements of the
container? The size stays the same. It seems to be working now, but I
thought I read somewhere something about this not always working out. Any
thoughts?
d
|
by: Dave Townsend |
last post by:
Hi,
Can anybody help me with the following piece of code?
The purpose behind the code is to parse HTML files, strip out
the tags and return the text between tags. This is part of a larger
application which will perform "searches" for text values in a
directory of html files, trying to match only the non-tagged text
in the documents.
|
by: Lasse Vågsæther Karlsen |
last post by:
I need to merge several sources of values into one stream of values. All
of the sources are sorted already and I need to retrieve the values from
them all in sorted order.
In other words:
s1 =
s2 =
s3 =
for value in ???(s1, s2, s3):
|
by: Jack |
last post by:
I have a class called "Base". This class has a protected member
variable "m_base" which can be retrieved using the public member
function "GetBaseMember". "m_base" is initialized to "1" and is never
changed.
I have another class which is a subclass of the "Base" class called
"Derived". This derived class has a member variable called
"m_derived". "m_derived" is initialized to "2" and is never changed.
I pass an array of "Base" classes...
| |
by: John Salerno |
last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part,
but it does in the second? Is the first statement something different?
False
print 'hi'
hi
Thanks.
|
by: Bo Yang |
last post by:
As long as I write c++ code, I am worry about the
pointer. The more the system is, the dangerous the pointer
is I think.
I must pass pointers erverywhere, and is there a way to
ensure that every object pointered by any pointer will
be deleted and only be deleted once?
|
by: desktop |
last post by:
1)
I have this code:
std::list<intmylist;
mylist.push_back(1);
mylist.push_back(2);
mylist.push_back(3);
mylist.push_back(4);
|
by: subramanian100in |
last post by:
Suppose I have
vector<intc;
for (int i = 0; i < 10; ++i)
c.push_back(i);
vector<int>::iterator it = find(c.begin(), c.end(), 5);
If I do,
c.insert(c.begin(), 10);
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |