Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> think I could come up with a python example that maps 1:1

My take on it:

    class Stuff:
        def __init__(self):
            self._list = [1, 2, 3, 4]
        
        @property
        def each(self):
            for el in self._list:
                yield el
    
    for item in Stuff().each:
        print(item)
It's even less verbose than the Ruby equivalent in the original article, thanks to the indentation-defined blocks.


AFAIK, there is no reason to use the form “for el in self._list: yield el”, unless you are running Python 3.2 or older.

Why not:

  each = self._list
Or, if you need to be able to re-assign self._list to a new object:

  @property
  def each(self):
    return self._list
Or, if you for some reason need it to return an iterator:

  @property
  def each(self):
    return iter(self._list)
Or, if you really want it to be a generator function:

  @property
  def each(self):
    yield from self._list




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: