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=1
35
Upvotes
r/programming • u/llimllib • Jun 29 '09
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