Created
October 19, 2021 20:45
-
-
Save Nimamoh/3d00d92a30810d562c1a21666768f979 to your computer and use it in GitHub Desktop.
generator.py
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
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