Skip to content

Instantly share code, notes, and snippets.

@Gera3dartist
Created June 4, 2018 15:17
Show Gist options
  • Save Gera3dartist/f285f0c8550d9ac67a8f2ca5920c8e47 to your computer and use it in GitHub Desktop.
Save Gera3dartist/f285f0c8550d9ac67a8f2ca5920c8e47 to your computer and use it in GitHub Desktop.
"""
Reference: https://www.python-course.eu/python3_generators.php
"""
def fibonacci():
""" generates fib sequence """
a,b = 0,1
while 1:
yield a
a,b = b, a + b
def test_fib():
counter = 0
for i in fibonacci():
print(i)
if counter > 12:
break
counter += 1
def gen_with_return():
yield 1
return # having return in generator is equivalent of raising StopIteration
def test_gen_with_return():
g = gen_with_return()
print(next(g))
print(next(g))
def send_in_coro():
"""
Coroutine can accept objects.
this demo intended to highlight this concept
"""
print("initialized generator")
x = yield
# do something with x
print("got value for x: {}".format(x))
yield x
yield x
def test_send_in_coro():
g = send_in_coro()
next(g)
print(g.send(10))
print(next(g))
def infinite_looper(word: str):
"""
Demoes how to send into generator messages
"""
count = 0
while True:
if count >= len(word):
count = 0
message = yield word[count]
if message != None:
count = 0 if message < 0 else message
else:
count += 1
def test_infinite_looper():
g = infinite_looper("abcdefg")
print(next(g))
print(g.send(1))
print(g.send(0))
print(g.send(6))
def main():
# test_fib()
# test_gen_with_return()
# test_send_in_coro()
test_infinite_looper()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment