Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
generator.py
from typing import Iterable, Iterator, Sequence
def range_gen(n=10):
"""Range implemented as generator"""
# It is used like an iterator,
# each time next() is called on this generator,
# code is resumed from yield clause.
# This allows for lazy computed iterators.
i = 0
while True:
if i >= n:
break
yield i
i += 1
def main():
gen = range_gen()
print(type(gen))
print(f"generator is an iterator? {isinstance(gen, Iterator)}")
print(f"generator is an iterable? {isinstance(gen, Iterable)}")
print(f"generator is a sequence? {isinstance(gen, Sequence)}")
print(f"Consuming the generator in a for-loop")
for i in range_gen():
print(i)
if "__main__" == __name__:
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment