6 ms·
I can understand the frustration caused by this kind of bug, but it's actually pretty easy to fix: generator = (x * x for x in xrange(10)) # A generator
by henryprecheur 17y ago
I can understand the frustration caused by this kind of bug, but it's actually pretty easy to fix:
generator = (x * x for x in xrange(10)) # A generator
my_list = list(generator) # Build a list, reusable
That's the Python way of doing things: trust the programmer, & let him make mistakes.
Also how does C# implement this kind of "smart" laziness? It seems to me there will be other more obscure problems: what happen if the Enumerable have side effect? Is the side effect repeated or is the result cached? Python's generator are implementation is simple: there's no tricks, magic, & layers of abstraction.
- mquander 17y agoIn C#, it's basically just idiomatic to produce enumerables that don't have side effects as you enumerate them. There's nothing strictly enforcing it. Like in your Python example, one is expected to put the results of an enumerable into a real data structure if you need it more than once and you suspect that the enumeration might be expensive or involve side effects. Both ways "let the programmer make mistakes" -- in C#, you might accidentally enumerate something more than once without realizing it, which may be inefficient or cause subtle bugs. In Python, you might accidentally screw something up the way the fellow writing the post above did. One might think that the C# behavior is overly clever, and it's best to fail fast, but it's convenient in practice when you know that cycling again won't cause problems (the majority of the time.) I'm not sure which I prefer. One thing to note is that having static types a la C# does make it clear at all points whether you are dealing with an enumerable or a real list.