r/programming • u/llimllib • Jun 29 '09
Python's iterators are a bad implementation of laziness
http://sandersn.com/blog/index.php?title=python_s_iterators_are_a_bad_implementat&more=1&c=1&tb=1&pb=118
u/dpark Jun 29 '09
Isn't this a case of do what I want and not what I say? i.e. A problem with the user, not with the construct?
If you consume the elements of an iterator, they are gone. How is the iterator supposed to know that you are attempting to reuse it? If you wrote something like this in Java, no one would take pity on you:
Iterator iter = // ...
while (iter.hasNext()) {
Object o = iter.next();
// ...
}
while (iter.hasNext()) {
// OH, NO! THIS NEVER EXECUTES!
}Why not? Because it's stupid. Reading the elements of an iterator is destructive. That's the nature of iterators. If you want to read the elements non-destructively, then don't use an iterator (or get a fresh iterator every time).
6
Jun 30 '09 edited Jun 30 '09
Reading the elements of an iterator is destructive. That's the nature of iterators.
...then don't use an iterator (or get a fresh iterator every time).
Which alludes to the essence of the quite legitimate complaint.
AFAIC, yes we should all be using a pure functional language for anything remotely practical. Yes we should keep complaining until this is largely accepted.
4
u/dpark Jun 30 '09
No it isn't
First, the paper you linked to is about internal iterators, rather than traditional, external iterators (such as are found in Python, C#, Java, C++, etc.). The paper says this on the first page.
Second, it would have been more correct to say that iterators are "stateful" instead of "destructive". However, in general, you can view iterators as destroying elements as you iterate. Particularly, if an iterator doesn't implement rewind functionality, then it is effectively destructive. Additionally, some iterators are truly destructive by their nature. e.g., An iterator that iterates over strings sent by a remote server will read strings and then discard them. The data in those previous strings is destroyed if you (the user) do not save them. Because of iterators such as these, the most general iterator is in fact destructive.
Which alludes to the essence of the quite legitimate complaint.
His complaint was that the iterator didn't automagically reset. He's the one using iterators directly. If he wants a new one, he needs to provide it. It is unreasonable to assume that iterators will reset itself. How is the iterator to know when it should reset? When it reaches the end? I see a whole class of subtle bugs arising from that, which would be far more sinister than his misuse of the iterators.
AFAIC, yes we should all be using a pure functional language for anything remotely practical. Yes we should keep complaining until this is largely accepted.
Um, okay. That's nice. If you want to use a pure functional language for your programming, have at it. I'm not sure how this is relevant, though.
4
Jun 30 '09
First, the paper you linked to is about internal iterators, rather than traditional, external iterators (such as are found in Python, C#, Java, C++, etc.). The paper says this on the first page.
Right, so iterators are not destructive by nature. Just a particular type of iterator, which exhibits problems, that are going to provoke complaint -- justifiably so. That paper is one of my favourites and I have read it many times. I have also implemented it for Scala (see Scalaz) which has a type system powerful enough to do so.
For what it is worth, the "essence of the iterator pattern" can be implemented in Python, C++ and to some extent (without the higher-kinded abstraction and so mandating O(n) code bloat where n = number of type constructors), Java and C#.
It is not what is found in these languages -- it is what many people believe is the canonical solution to "the problem of iteration", which is not a solution at all -- but a pervasive problem of the side-effects of "typical" iterators -- as per the original complaint, which is perfectly justified.
I'm not sure how this is relevant, though.
That's part of the reason this problem persists. I wish more people could see the relevance. I suspect the original complainant doesn't see the relevance either and so is prone to perpetually fumbling in the dark.
I have lectured for years and I gave up, but I continue to lobby for a better education regime. What else can I do?
1
u/dpark Jun 30 '09
Right, so iterators are not destructive by nature. Just a particular type of iterator, which exhibits problems, that are going to provoke complaint -- justifiably so.
Yes, just a particular type of iterator, which happens to be the most common type, and which happens to be what most developers are referring to when they speak of iterators, and which the paper you link referred to as traditional, and which is more flexible than the internal iterator the paper describes. Yes, that type of iterator is, in its typical and most general form, destructive.
It is not what is found in these languages -- it is what many people believe is the canonical solution to "the problem of iteration", which is not a solution at all -- but a pervasive problem of the side-effects of "typical" iterators -- as per the original complaint, which is perfectly justified.
There's nothing wrong with the typical iterators. They are quite powerful, and extremely useful. Certainly, there are other forms of iterators. Complaining about state or side effects isn't especially useful when programming in a language that's not purely functional, though. Yes, typical iterators have state and side effects. So what? Typical languages have state and side effects. Replacing typical iterators with internal iterators would result in less powerful iterators that do not work in conjunction with some programming needs.
That's part of the reason this problem persists. I wish more people could see the relevance. I suspect the original complainant doesn't see the relevance either and so is prone to perpetually fumbling in the dark.
Let me clarify my statement. I don't see the relevance in discussing pure functional languages in the context of Python. Python is not purely functional. It is very much a hybrid language, like most successful languages (though more functional than some).
Purely functional languages have a lot of elegance, and it can certainly be nice to discuss the nifty things that are possible in pure languages. But in the context of Python, these things are not really relevant. Yes, X, Y, and Z might be different or better in a pure language. Q, R, and S might be better in Ada, too. These might be nice to know, but they don't really matter to the conversation at hand, which revolves around Python.
I have lectured for years and I gave up, but I continue to lobby for a better education regime. What else can I do?
Pain killers? I hear it takes the edge off. :)
Seriously, I think the move towards more functional languages is a good thing. I don't think we will ever be programming in purely functional languages for mainstream work, though. It won't be practical, just as purely object-oriented languages have not proven practical. Functional languages have been around for a long time and haven't taken over. The most popular all have non-pure aspects. Even Haskell allows poking holes in its elegance for the sake of performance. Compromise languages tend to win out, because they are simply so much more flexible. Working in a purely functional language isn't magically better than working in a purely procedural language. It's just different. They both have their strengths and weaknesses. The best languages are probably all going to land somewhere in between.
5
Jun 30 '09 edited Jun 30 '09
I hope you don't mind. You made some mistakes.
which the paper you link referred to as traditional, and which is more flexible than the internal iterator the paper describes.
This is wrong. The other way around. But it does raise an interesting point.
You can define the mutable iterator from the traversable -- but not the other way around. If the opposite were true, then we wouldn't have the problems that the original complainant is discussing. In other words, side-effects are pervasive -- and not just a little.
Complaining about state or side effects isn't especially useful when programming in a language that's not purely functional, though.
This is wrong. It's very worthwhile. I complained to myself about Scala's poor iterators and rewrote them more elegantly -- I benefit as a result. This was worthwhile.
Let me clarify my statement.
No let me clarify. When I say "we should be using pure functional languages" I don't necessarily mean because they transcend this problem (which they do). To the extent that we are not using purity -- regardless of language -- is the same extent to which we should concede that we will run into the given problem over and over. In other words, if you're going to do it the shitty way, you have a few choices:
Complain that it's shitty and potentially learn that there is a better way (which there is ala Traversable).
Pretend that a shitty solution is not shitty and forever suffer the result through a series of self-deluded apparent tautologies.
Concede that the shitty way is shitty and accept the large penalty.
Do not concede, harden up and program properly.
At what point do we all just harden up and begin using languages that are more amenable to more practical programming? If not languages, then at least programming techniques (yes, Python, C++, Java, C# -- it's all doable). This was my point.
1
u/dpark Jun 30 '09
I hope you don't mind. You made some mistakes.
I normally do. :)
This is wrong. The other way around. But it does raise an interesting point.
I was basing that statement on a few lines from the first page. They clarify that external iterators are "traditional", but that they are using "iteration" to refer to internal iterators. They also state that external iterators are more powerful than internal iterators.
I'll be honest. I pretty much read the first section and then stopped. I've waded through several hundred pages of Haskell papers, and I wasn't really in the mood for another twenty-something pages dedicated to iterators. But now I've embarrassed myself by speaking without fully reading it, so I'll have to save it for later.
I complained to myself about Scala's poor iterators and rewrote them more elegantly ...
I don't think the original author has any intention of rewriting Python's libraries to handle iterators differently, though. I know I don't. Certainly, if there's a better way to do something, and you'll get the benefit of implementing it, then do so. I don't think anyone's doing that for Python right now, though.
No let me clarify. When I say "we should be using pure functional languages" ...
I guess what I'm missing is why traditional iterators are so shitty. Are they perfect? No, but I'm not aware of much that is. The problem the original author ran into is, in my opinion, not especially significant. Yes, it's possible to misuse traditional iterators. It's also perfectly possible to use them correctly. Lots of people do so. Now, if you can explain why traditional iterators are so shitty, and why the alternative is so much better, then I'd love to hear it. But honestly, if it takes a 20+ page academic paper to demonstrate, then I have my doubts about its importance.
Now, you're probably speaking more generally, but I don't believe that pure functional languages are problem-free by any means. I feel like moving from, say, Java to Haskell is just a case of trading problems. Sure, problems that are directly caused by state are avoided, but so are the benefits afforded by state (unless you awkwardly punch holes into Haskell's purity.) Shoving everything into a monad is not, in my opinion, especially practical. I find that far more awkward than, say, traditional iterators.
At what point do we all just harden up and begin using languages that are more amenable to more practical programming? If not languages, then at least programming techniques (yes, Python, C++, Java, C# -- it's all doable). This was my point.
I'm fine with using better techniques were available. I just don't believe that moving to pure functional programming is better. I believe it's different. I also believe that the most fertile ground is found in the area between the extremes. Impure languages (and techniques) dominate, and I believe will continue to. The constraints imposed by pure functional programming outweigh the benefits, in my opinion, and seemingly in the opinion of the programming community.
I think the best languages will continue to incorporate more from the functional end of the spectrum, but I don't believe that pure functional programming will become mainstream. The most popular functional languages are impure, and I believe there are reasons for that.
2
u/humpolec Jun 29 '09 edited Jun 29 '09
The problem is that Python encourages use of iterators. In Java the default is to use a foreach loop over a collection.
Edit: OK, maybe it doesn't "encourage" it as much as makes it easy to confuse iterators with collections - see bobindashadows' comment.
6
u/dpark Jun 29 '09 edited Jun 29 '09
Why is that a problem? I'm not a Python guy, so maybe I'm missing something. The C++ STL heavily uses iterators, and no one's consuming elements of iterators and then expecting them to still be around.
If you think of iterators as pointers (which is basically what they are), the appropriate use should be pretty obvious. e.g. If you increment the pointer all the way past the last element, don't expect it to still be pointing to the first element next time you try to use it.
Now, if you're saying that Python should have functions expecting "iterables" instead of "iterators", then I'd agree that's probably true.
P.S. Upvoted because others downvoted you.
2
u/humpolec Jun 29 '09 edited Jun 30 '09
C++ STL has immutable iterators - nothing silently 'consumes' elements if you pass an iterator by value; it will not change your copy. Just like pointers.
Python has stateful iterators masquerading as collections - well, maybe masquerading isn't a good word for this, but you can use them in places where a collection is expected (for, str.split, etc.) which can lead to unexpected behaviour, like in the article.
2
u/dpark Jun 30 '09
That's a good point. The STL works with copies of the iterators instead of modifying them directly. I guess a better comparison would be Java, where iterators have reference semantics (though fewer methods take iterators directly in Java).
I think the only real issue is that iterators in Python are also iterable, returning themselves in response to
iter(). I agree this is somewhat strange, and probably not a good idea. The only benefit I see is that it makes it easier to work with generators, but the appropriate fix there is to have generator classes be instances of iterable, and return iterators when requested, like collections. The approach Python took is awkward, but I don't think it's a massive problem.2
u/humpolec Jun 30 '09
the appropriate fix there is to have generator classes be instances of iterable, and return iterators when requested, like collections.
That's not without its own set of problems - if the generator class has to allow several iterations over it, it either has to store the results somewhere (and they can get too long for that - Haskell and Clojure solve it by allowing part of collection to be GC'd) or execute the generator procedure for the second time (but that may not be possible, for example if the procedure reads from a socket).
2
u/dpark Jun 30 '09
I agree. The more I think about it, the less I'm convinced that there's a perfect way around the issues. It's a tradeoff, and I think the Python approach is as reasonable as any other. Making iterators not look like collections (e.g. not being iterable) has some issues. Making generators be iterable has some issues. There are some issues no matter what we do, and it seems that issues with the current implementation are pretty minor.
26
Jun 29 '09
No, iterators are an implementation of iterators.
They can be used to emulate laziness to a certain extent. But the idea to consume iterators more than once is just wrong and absolutely not intended. If you really want to, there is still itertools.tee.
That guy did not really get the concept and the beauty of python iterators being able to be consumed (see the talk by Dave Beazly).
3
17
u/yogthos Jun 29 '09
A perfect example of why laziness and state do not mix well. This sort of bug is extremely easy to make, and the only indication of its existence will be the incorrect output. It may be easy to miss in testing and a nightmare to debug.
0
u/timmaxw Jun 29 '09
A perfect example of why laziness and state do not mix well.
No. A perfect example would be if some mutable data that the generator depended on were modified by a different function before the generator had finished iterating. This is really just a problem with state and Python's misleading conventions about the state of an iterator.
5
Jun 29 '09
.NET's IEnumerator suffers the same problem. One might say that IEnumerable is a "solution" -- I prefer to call it "another problem".
4
Jun 29 '09 edited Jun 29 '09
I've been bitten by this problem in the past but you get used to it. Sometimes I used a decorator like this if I want to generate a list result from a generator:
def genlist(fun):
def wrapped(*args, **kwds):
return list(fun(*args, **kwds))
return wrappedAs a general rule, don't iterate a sequence which is passed as an argument or returned from a function more than once unless you know for sure it's not a generator.
4
Jun 29 '09
So he wrote a function which expects a list of characters, and then passed it a generator instead. And then he was surprised when it acted weird.
How is that really any different from:
def repeatString(s):
return s * 2
a = repeatString(4) # WTF!? I expected "44" but instead I got 8!2
Jun 30 '09
It is more like:
remainder((e() + e()) / 2) == 0Expected true regardless of the return value of e(), got false.
14
u/humpolec Jun 29 '09
I agree. Lazy, stateless, memoized sequence (like in Haskell and Clojure) would be much better than iterator.
But probably un-Pythonic.
4
0
u/Smallpaul Jun 29 '09
Are Haskell sequences memoized by default?
2
u/Seppler9000 Jun 29 '09
Short answer: Yes, because once a value is computed, it sticks around (until it gets garbage collected). This is why you run out of memory if you try to find the end of an infinite list while a reference to the beginning of the list is still in scope.
5
u/Felicia_Svilling Jun 29 '09
"Lazy, stateless, memoized sequence" is actually a bit redundant. Lazyness implies memoization, otherwise it would be call by name instead.
4
u/Smallpaul Jun 29 '09
I've read that comment about seven times and still don't understand. If you feel like filling in the details, then please do so. Otherwise, do not bother.
If I have a sequence that represents all of the characters in Unicode, generated one at a time, you're saying that Haskell by default would cache the entire thing in memory "in case" I wanted to iterate over it a second time. According to Seppler9000 it would do this as long as I maintain a reference to the start of it as I'm iterating.
Your position is that this is what Haskell must do as a Lazy language. There is no other implementation choice. It cannot discard the sequence contents and re-compute them on demand. If it did that, it would be a "call by name" rather than "lazy" language.
3
u/Seppler9000 Jun 29 '09
Haskell is technically defined as non-strict, which is a superset of both lazy evaluation and call by name. There are non-lazy implementations of Haskell, but I don't think anyone has ever done call by name.
2
u/Felicia_Svilling Jun 29 '09 edited Jun 29 '09
Yes, all this is correct, this is the definition of laziness. I dont see any other details that could be filled in. Although to be fair there are implementations that isnt strictly lazy.
And you could always just wrap your unicode character sequence in a function. I belive most haskell implementations would then recalculate it whenever you call it.
1
u/bgeron Jun 29 '09
I belive most haskell implementations would then recalculate it whenever you call it.
I think this kind of stuff needs to go in the language standard.
8
u/munificent Jun 29 '09
In C#, you don't pass around the raw mutable generator (IEnumerator in C# parlance), you pass around an immutable IEnumerable. IEnumerable has a single function: GetEnumerator() that creates a fresh generator each time it's called.
Does Python have anything like this? Maybe this is just my C# perspective, but passing around the raw generator seems seriously hokey.
4
u/theeth Jun 29 '09
You can pass around the function or method that returns the iterator, it's basically the same.
2
u/dfj225 Jun 29 '09 edited Jun 29 '09
Part of Python's iterator interface is the
__iter__method, which should return an iterator for the object defining it.Here's my silly example:
class Foo(object): def __iter__(self): return iter([1,2,3]) In [2]: foo = Foo() In [3]: for f in foo: ...: for f2 in foo: ...: print "(%d,%d)" % (f, f2) ...: (1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3)In this case, the "in" operator calls
foo.__iter__()to get a copy of the objects iterator. This should be a new iterator for each invocation. If a generator was returned instead of an iterator, the behavior would be the same.2
u/theeth Jun 29 '09
The problem the author had is that he wasn't doing that. He was doing this:
foo = [1,2,3] i = foo.__iter__() for f in i: for f2 in i: print f, f2 1 2 1 33
u/dfj225 Jun 29 '09
Right and that is not the correct way to use an iterator given the desired behavior.
Given the munificent's question, I suppose it'd be like using a single C# IEnumerator object. I don't know C#, but I'd expect there to be the same bug if the iterator is used more than once.
1
u/munificent Jun 29 '09
That's correct. An IEnumerator maintains the current location in the collection, so reusing won't work unless you manually reset it.
1
-2
u/Seppler9000 Jun 29 '09
Did you read the post? Did anyone? This is exactly how he wants it to behave.
4
3
u/munificent Jun 29 '09
Did you read the post?
Yes, I did. I read him saying that Python iterators aren't like IEnumerable. My question was whether or not Python did have something like IEnumerable.
1
u/bgeron Jun 29 '09
Nope. You can either require a sequence and loop over that, or convert the iterator to a sequence with
listwhen you use it.-3
Jun 29 '09 edited Jun 29 '09
You can use the iter() function to get a "fresh" iterator, but otherwise I agree with your assessment.
0
u/exogen Jun 29 '09
But this will not solve the author's problem.
2
u/niviss Jun 29 '09
why not?
4
u/exogen Jun 29 '09
Both iterators given by iter() will share the same source generator and consume its items. Actually, netytan's statement was false in the first place - calling
iter()on a generator just returns the same generator object, since generators conform to the iterator protocol and that'siter()'s only promise. But even if it did return a "fresh" iterator, it still wouldn't work.1
u/Brian Jun 30 '09
Yes - you'd need to use something like
i1,i2 = itertools.tee(iter)which will return two or more copies (or at least objects that act like a copy) of the iterator by buffering objects that haven't been consumed by both iterators.
7
u/mythin Jun 29 '09
def fix(node):
snode = ''.join(node)
if snode==')':
return 'RRB'
elif snode=='(':
return 'LRB'
else:
return '-'.join(map(str.strip, reversed(''.join(node).split(','))))Why would you do it this way? He's doing: ''.join(node) twice...why not just use the result of the first one in place of the second one?
def fix(node):
snode = ''.join(node)
if snode==')':
return 'RRB'
elif snode=='(':
return 'LRB'
else:
return '-'.join(map(str.strip, reversed(snode.split(','))))Much cleaner, doesn't have the bug he's worried about, and performs less work.
6
u/niviss Jun 29 '09
why? he actually mentions why!
Can you see the bug? No? Well, I do a little work twice, joining a list of chars into a string: snode = ‘’.join[node]. I wasn’t sure that this ad-hoc checking for parentheses would work so I didn’t want to refactor the original expression, which also contains ‘’.join(node).
4
u/mythin Jun 29 '09 edited Jun 29 '09
But that sentence doesn't actually say anything useful. Sure, he didn't want to make giant changes that he would just have to change back if the checking for parentheses didn't work. I understand that, but he's still making complaints about a bug that wouldn't exist if he had continued to refactor.
Apparently he also doesn't use version control, otherwise undoing his changes would be super simple.
I would be a little more sympathetic if this was a larger function with a lot of moving parts he was refactoring. As is, he's refactoring a one liner into a 7 liner. It's not hard, in that case, to do it right the first time.
My question still stands: why would you refactor, but at the same time avoid refactoring because you might be doing it wrong?
2
u/niviss Jun 30 '09
because the first refactor is needed, the second refactor wasn't, I imagine the dude was just interactively testing the code and didn't thought it would cause a bug.
As mentioned in other comments, the issue is that both lists and generators have a similar interface, but can't be exchanged, and that using generators for lazyness can bite you in the ass if you didn't know what you were getting. It doesn't matter if the refactor mattered in this case or not.
2
Jun 29 '09
Pythons iterators are great for the specific case they were designed for. If you look at something like Icon, where the concept of a generator is baked into the semantics of the language, you'll be pleasantly surprised. In fact, I prefer goal-directed evaluation over lazy evaluation.
2
u/lost-theory Jun 30 '09 edited Jun 30 '09
The biggest benefit of using iterators/generators/etc. comes from programming in a side-effect free, functional style.
You will run into ugliness if you try to 're-use' an iterator the same way you would use a list. That's not a bad implementation of laziness in my opinion.
6
u/nextofpumpkin Jun 29 '09
I am at a loss to figure out what is wrong here. Does he want looping generators? Or are they not really generators? Or does he want generators that are drop-in substitutes for lists?
7
u/inmatarian Jun 29 '09
Probably that he was expecting the iterator to be memoized for him so he could inspect the list of items, while still getting the benefits of lazy evaluation. In a case like this, he's probably better off evaluating the whole list when he first gets it, and then passing the tuple around.
9
Jun 29 '09
I didn't read the whole pile of poo, but I think he's just complaining that debugging is more difficult when you're dealing with a lot of generators. Did he think laziness was free?
14
4
u/bart2019 Jun 29 '09
I think he's just complaining that debugging is more difficult
No... He's complaining that there is a bug, at all.
2
u/yogthos Jun 29 '09
well it does work the way you expect in other languages :)
Since I keep hearing that python is supposed to be intuitive and all, and encourage writing code that's self evident, seems like this is a bit of a problem here. You can write code that intuitively seems correct, it will compile and run, but will produce faulty output. The language should address cases like this and at the very least issue a warning.
24
Jun 29 '09
I keep hearing that python is supposed to be intuitive.
This is a common misconception – Python was designed to be intuitive to GvR.
-7
u/Smallpaul Jun 29 '09
That's a cop-out. And not very helpful as a design criterion.
2
u/earthboundkid Jun 30 '09
Quoth the Zen:
There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch.
3
u/nextofpumpkin Jun 29 '09 edited Jun 29 '09
Well, what do you mean the way you'd expect? This behavior seems perfectly reasonable to me; generator instances are completely destructive in Python in the sense of element consumption.
1
u/yogthos Jun 29 '09 edited Jun 29 '09
What I expect is if a language that claims to be "the new vb" provides a feature, it would be intuitive to use the said feature. Seems like there already was a way to do what the iterators do that behaved the way you'd expect it to. A new feature was introduced which allows you to do the same thing in a different way, and lo and behold it is also easy to fuck up and produce hard to find bugs with.
I recall when people argued against the inclusion of TCO in python, that one of the reasons it shouldn't be included is because apparently it's hard to reason about. Well I think the same argument applies here too, if TCO it didn't pass the bar why does this?
Seems like the whole ease of learning and consistency applies sort of arbitrarily in python, if it's a feature Guido likes then no need to worry about it being error prone or confusing to developers, if it's something Guido doesn't like then let's pretend that people can't figure out what a tail call is or some shit.
2
u/Brian Jun 30 '09 edited Jun 30 '09
Seems like there already was a way to do what the iterators do that behaved the way you'd expect it to
No, C#'s enumerators don't behave like this either. What it does do different is forbid iteration over IEnumerators in foreach loops, whereas python has iterators implement the equivalent of the IEnumerable interface, meaning for loops will iterate over them, picking up from the point they are currently at.
This means that this problem never occurs in C# because it doesn't allow you to operate in this way (unless you implement it by hand by manually iterating, or manually make it by creating a proxy IEnumerable that returns an existing IEnumerator). However, being able to iterate over partially consumed iterators is actually very valuable. For instance, "process this file from the current point". Forbidding it loses you significant flexibility and convenience.
There's no way to do what he wants (restart the iterator in the second for loop) completely generally without memoizing all the values (which defeats the purpose), as there's no guarantee that the iterator can restart - it may have side effects, such as itself be consuming from a non-rewindable stream (eg. a network connection).
You can do from some specific instance that supports it, by going back to the original IEnumerable you are consuming from, but this is just as doable in python - ie. reinvoke the generator, or call
iter()on the original iteratable. If all you have is an iterator though, there's no way to get the original IEnumerable, in either python or C#.1
u/yogthos Jun 30 '09 edited Jun 30 '09
I was not referring to enumerators actually, the proper way to do this of course would be with first order functions like map. But people say FP is hard, so instead they choose all these problems that come from twiddling the state to do anything and create a lot of unnecessary complexity while doing it. You take something simple like iteration of a data structure and then you create a bunch of edge cases and then you spend your time figuring out what went wrong instead of getting shit done.
2
u/Brian Jun 30 '09
the proper way to do this of course would be with first order functions like map.
Using higher order functions seems entirely orthogonal to how to represent lazy sequences. Exactly the same issue occurs if you use map as well. The relevant part of FP that would help here is being side-effect free, and even there you will need to do something like memoize the generator if used multiple places in the same expression. (The side-effect free advantage means that this can be done automatically though)
1
0
Jun 30 '09
[deleted]
-1
u/yogthos Jun 30 '09
doing it well would involve throwing a warning saying that you're using the iterator twice, just saying.
2
u/earthboundkid Jun 30 '09
They do warn you. Closed iterators throw
StopIteration. The only issue is there's no easy way to tell if that's because it just closed naturally or because it was already closed earlier. In either case,forautomatically detects it and finishes the loop.0
Jun 30 '09
it's intuitive if you don't expect to do contortions as a matter of course.
sort of like complaining about the narrowness of the door when you've been expecting to crab walk sideways through it because that's how it's done everywhere else.
1
u/ishmal Jun 30 '09
I agree. I actually think it's a good thing for sources with different behaviours to be able to follow the same API. "Not working the way I want it to work" is not necessarily a bug.
1
u/iamjack Jun 29 '09
Yeah, I'm not sure either... how's Python supposed to know he wants to restart the generator anyway? Because he used it again? Regardless, it's stupid to use generators here in the first place (even though he didn't want to refactor the expression) because you're evaluating everything in the sequence twice anyway...
1
0
0
Jun 29 '09
[deleted]
4
u/bgeron Jun 29 '09
I have. Sometimes, it's really easy to write a function as a generator, and use the generator in a for loop or two. Then after some days I re-read the for loops and think "Hey, that function must have returned a sequence", and I do other stuff with the 'sequence'. Then the fun starts.
-5
u/LoKi128 Jun 30 '09
So the problem is that the IDE is not reminding you of what type the function returns, or if is a generator or not.
2
u/timmaxw Jun 29 '09
I've never made the mistake that he made, but I often find myself converting generators into lists to avoid this issue. I would appreciate the C#-style solution.
2
Jun 30 '09 edited Jun 30 '09
I think this comment is relevant to your confusion
"Make something idiot proof and someone will build a better idiot"
0
Jun 30 '09
I also like, "Never argue with an idiot, they will bring you down to their level and beat you with experience", not 100% relevant, but true none the less.
1
0
38
u/bobindashadows Jun 29 '09 edited Jun 29 '09
The problem is that Python promotes the use of identical syntax for multiple, similar representations of data. Examples:
Gives:
Next:
Gives:
Next:
Gives:
This is great, because duck typing means we don't need to explicitly state which type an object has, we simply need to know to which methods it responds. By defining standard interfaces and syntaxes, we know that we can expect
", ".join(map(str, foo))to work iffoois enumerable. So, if we have a function that takes an enumerable object as an argument, it should work if we change its parameter from a tuple to an array, or from an array to a range. However, if we then switch it to a generator because our input is now too large to load into memory all at once (for example):Gives:
This is a valid concern, because it does not match other enumerable objects. One might argue that this is a contrived example (it is), and that if you are switching your code to use generators, it is probably for reasons of efficiency. If you're optimizing your code, then you shouldn't be using a generator twice like I've done here, that's just silly. And you'd be right.
However, the person reading the code expects calling
", ".join(map(str, foo))twice to take twice as long, and it's far easier to debug that than your enumerable object suddenly containing no objects halfway through a function definition, because you switched its data type in another part of the program.EDIT: I suck at markdown