Skip to content

Instantly share code, notes, and snippets.

@fisher6
Created September 11, 2017 20:24
Show Gist options
  • Save fisher6/b81c9253eeb5e052445cae72ac0e786f to your computer and use it in GitHub Desktop.
Save fisher6/b81c9253eeb5e052445cae72ac0e786f to your computer and use it in GitHub Desktop.
# implemention for (each) loop in python as a function.
# Example:
# forr([1,2,3], print)
# is the same as
# for item in container:
# print(item)
def forr(cont, func):
""" forr(cont, func) == for x in cont: func(x) """
iterator = iter(cont) # or iter.__cont__
while True:
try:
func(next(iterator))
except StopIteration:
break
@fisher6
Copy link
Author

fisher6 commented Jan 18, 2018

In [26]: class l:
    ...:     def __init__(self):
    ...:         self.ll = [1,2,3]
    ...:     def next(self):
    ...:         if self.ll:
    ...:             return self.ll.pop()
    ...:         raise StopIteration
    ...:     def __iter__(self):
    ...:         return self
    ...:     
    ...:     

In [27]: g = l()

In [28]: for i in g:
    ...:     print i
    ...:     
3
2
1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment