3 ms·
Honestly, I'm not sure if you can do that in Python - one of the side-effects of not writing classes in Python is that I'm also ignorant of the behind-the-scene
by scott_s 15y ago
Honestly, I'm not sure if you can do that in Python - one of the side-effects of not writing classes in Python is that I'm also ignorant of the behind-the-scenes stuff that goes on with them.
You may be able to get something close to what I wrote with a function that returns a closure, but I don't think you can get exactly the for x in y syntax. As explained in another post on HN's front page, "A Guide to Python's Magic Methods": http://www.rafekettler.com/magicmethods.html#sequence http://www.rafekettler.com/magicmethods.html#sequence, you need to define the __iter__(self) method on an object to support that style of iteration. (And that method needs to return an iterator object.)
And that brings us back to the same point I already made, but I think it's so important that I'll say it again: the abstractions you choose to represent concepts in your program will be determined by what is easy in the language you're using.
- gruseom 15y agoAh I didn't realize Python's limitations (if it has them here) were part of the mix. I strongly agree with your general point and will go one further: this has a huge impact on the kind of system that over time gets developed in that language. It conditions what gets written, which conditions what's easy to do next and eventually what's possible to do next. By making different things easy, languages bias the programmer toward thinking different thoughts. I wish more people would figure this out: it would make discussion of these things much more interesting. (Instead, all we really do is comparison of code snippets in different languages, which kind of misses the whole point.)
- scott_s 15y agoSomething that the objects I had in mind have in common: they're resources. They fundamentally require a handle, and associated functions that accept that handle as a parameter. There already is a tight coupling between the resource handle and those functions. Such resources, off the top of my head: files, sockets, locks, condition variables.
- BrandonM 15y agoA function that yields instead of returning values results in an iterator. One does not need to define a class at all.
- empthought 15y agoCheck it out... def fibonacci_sequence(): a, b, c = 0, 0, 1 while True: a = b; b = c; c = a + b yield b >>> fibonacci_sequence() <generator object fibonacci_sequence at 0x108055550> >>> list(itertools.islice(fibonacci_sequence(), 0, 10)) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> for n in fibonacci_sequence(): print n if n > 13: break 1 1 2 3 5 8 13 21 >>>
- scott_s 15y agoYes, I had forgotten about generators, pjscott and jules provide great examples for the csv case above.