Skip to content

Instantly share code, notes, and snippets.

@miikka
Created September 23, 2015 14:03
Show Gist options
  • Save miikka/e16add1c196b7b5eecae to your computer and use it in GitHub Desktop.
Save miikka/e16add1c196b7b5eecae to your computer and use it in GitHub Desktop.
import inspect
DONE_ONCE = set()
def only_once():
"""Use as a generator to run a block only once."""
frame = inspect.stack()[1]
# frame is (frame object, path, line, ...)
key = (frame[1], frame[2])
if key not in DONE_ONCE:
DONE_ONCE.add(key)
yield
for i in range(2):
for _ in only_once():
print "iteration", i
# prints:
# iteration 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment