Skip to content

Instantly share code, notes, and snippets.

@P4
Last active December 14, 2015 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save P4/5125801 to your computer and use it in GitHub Desktop.
Save P4/5125801 to your computer and use it in GitHub Desktop.
Re-implement Python's for statement using @decorator syntax
#! /usr/bin/python
def foreach(iterable):
def iterate_over(func):
iterator = iter(iterable)
while True:
try:
value=next(iterator)
func(value)
except StopIteration:
break
return func # your function can be used later as if nothing happened
return iterate_over
if __name__ == '__main__':
a = list(range(15))
@foreach(a)
def thing(i):
print(i)
# equivalent to
# for i in a:
# print(i)
@aukaost
Copy link

aukaost commented Mar 12, 2013

wat

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