Created
January 23, 2016 15:14
-
-
Save alexaleluia12/6230f767eaac8c556f32 to your computer and use it in GitHub Desktop.
yield python
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
# mais informações sobre yield generator/coroutine | |
# http://www.dabeaz.com/generators/ | |
# motivação | |
# http://www.dabeaz.com/coroutines/Coroutines.pdf pg: 68 | |
""" | |
>>> gen = foo1(lambda : [1,2,3,6,90]) | |
Na função abaixo `ls = yield fn()` tem dois papeis deferentes | |
Primeiro momento `next(gen) ou gen.send(None)` vai retornar a chamada de `fn()` | |
ls tem None, esse valor retornado não tem nenhuma relação com as | |
proximas execuções do `gen` | |
No segundao `gen.send(iteravel)` o `iteravel` é atribuido a ls depois | |
cai no for executa o print e para no `yield` | |
""" | |
def foo1(fn): | |
""" | |
Retorna um generator | |
""" | |
ls = yield fn() | |
for i in ls: | |
print("$>", i) | |
yield # suspende foo1, quando voltar ainda vai estar dentro do for | |
# para retormar a execução pode ser: `next(xgen)` ou xgen.send(xx) | |
# mas apartir desse momento send() não vai fazer efieto dentro do | |
# for | |
""" | |
# exeção | |
>>> la = lambda : [2,3,4,7] | |
>>> la | |
<function <lambda> at 0x7f35575455f0> | |
>>> a = foo1(la) | |
>>> next(a)# == a.send(None) ## necessário para inicilização do generator | |
[2, 3, 4, 7] | |
>>> next(a) | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "studo-yield.py", line 5, in foo1 | |
TypeError: `NoneType` object is not iterable | |
>>> lb = lambda : [9,8,7,65] | |
>>> a = foo1(la) | |
>>> a.send(None) | |
[2, 3, 4, 7] | |
>>> a.send(lb)# agora o valor passado eh atribuido direto ao ls, sem ser chamado `lb()` | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "studo-yield.py", line 5, in foo1 | |
TypeError: `function` object is not iterable | |
>>> a.send(lb()) | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
StopIteration | |
>>> a = foo1(la) | |
>>> a | |
<generator object foo1 at 0x7f3557532aa0> | |
>>> a.send(None) | |
[2, 3, 4, 7] | |
>>> a.send(lb()) | |
(`$>`, 9) | |
>>> next(a) | |
(`$>`, 8) | |
>>> next(a) | |
(`$>`, 7) | |
>>> next(a) | |
(`$>`, 65) | |
>>> next(a) | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
StopIteration | |
>>> | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment