Created
August 7, 2019 18:57
-
-
Save dhaffner/9c0157bdac6deb5634e54027b96113c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
oh yes you gave me an idea.