Last active
July 7, 2019 16:07
-
-
Save amitkc00/f20aa4ed0e34559b09ac39be3f5d5649 to your computer and use it in GitHub Desktop.
Python Generators
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
# Reference : http://book.pythontips.com/en/latest/generators.html | |
def gen_func(): | |
for i in range(3): | |
yield i | |
gen = gen_func() | |
# Both the dirs below are different. I initially | |
# thought they be same but I think the language | |
# semantics mean something different here. | |
# I think gen has elements it can iter, | |
# whereas gen_fun is just holding the function | |
# that has ability to create an iterable object | |
print(gen_func.__dir__()) | |
print(gen.__dir__()) | |
print(next(gen)) | |
print(next(gen)) | |
print(next(gen)) | |
print("#####################") | |
# generator version | |
def fibon(n): | |
a = b = 1 | |
for i in range(n): | |
yield a | |
a, b = b, a + b | |
gen = fibon(3) | |
# Both gen and fibon holds an iterable object | |
# And hence their __dir__ is exact same. | |
# fibon().__dir__() is not a valid call. It needs | |
# fibon(3).__dir__() | |
print(fibon(3).__dir__()) | |
print(gen.__dir__()) | |
print(next(gen)) | |
print(next(gen)) | |
print(next(gen)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment