Skip to content

Instantly share code, notes, and snippets.

@dhaffner
Created August 7, 2019 18:57
Show Gist options
  • Save dhaffner/9c0157bdac6deb5634e54027b96113c5 to your computer and use it in GitHub Desktop.
Save dhaffner/9c0157bdac6deb5634e54027b96113c5 to your computer and use it in GitHub Desktop.
import inspect
from random import random
def foo_iterator():
while True:
caller_frame = inspect.currentframe().f_back
frame_info = inspect.getframeinfo(caller_frame)
if '.send(' in frame_info.code_context[0]:
yield f'.send()'
else:
yield ' next()'
def bar_randomizer(repetitions):
iterator = foo_iterator()
# Calling .send() before the first iteration will result in a
# TypeError exception
next(iterator)
for x in range(repetitions):
# Randomly call either iterator.send(x) or next(iterator)
if random() > 0.5:
y = iterator.send(x)
else:
y = next(iterator)
print(y)
print(f'Looped for {repetitions} repetitions.')
if __name__ == '__main__':
bar_randomizer(15)
@jefcolbi
Copy link

oh yes you gave me an idea.

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