update from Atlas
This commit is contained in:
87
attic/control/adder/coroadder.py
Normal file
87
attic/control/adder/coroadder.py
Normal file
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(10)
|
||||
10
|
||||
>>> adder.send(20)
|
||||
30
|
||||
>>> adder.send(30)
|
||||
60
|
||||
>>> try:
|
||||
... next(adder)
|
||||
... except StopIteration as exc:
|
||||
... result = exc.value
|
||||
...
|
||||
>>> result
|
||||
Result(sum=60, terms=3, average=20.0)
|
||||
|
||||
|
||||
Closing a coroutine:
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(1)
|
||||
1
|
||||
>>> adder.send(10)
|
||||
11
|
||||
>>> adder.close()
|
||||
>>> try:
|
||||
... next(adder)
|
||||
... except StopIteration as exc:
|
||||
... exc.value is None
|
||||
...
|
||||
True
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import collections
|
||||
|
||||
Result = collections.namedtuple('Result', 'sum terms average')
|
||||
|
||||
|
||||
def adder_coro(initial=0):
|
||||
total = initial
|
||||
count = 0
|
||||
while True:
|
||||
try:
|
||||
term = yield total
|
||||
except GeneratorExit:
|
||||
break
|
||||
if term is None:
|
||||
break
|
||||
total += term
|
||||
count += 1
|
||||
return Result(total, count, total/count)
|
||||
|
||||
|
||||
def prompt():
|
||||
while True:
|
||||
try:
|
||||
term = float(input('+ '))
|
||||
except ValueError:
|
||||
break
|
||||
yield term
|
||||
|
||||
|
||||
def main(get_terms):
|
||||
adder = adder_coro()
|
||||
next(adder)
|
||||
for term in get_terms:
|
||||
adder.send(term)
|
||||
try:
|
||||
next(adder)
|
||||
except StopIteration as exc:
|
||||
result = exc.value
|
||||
print(result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
get_terms = (float(n) for n in sys.argv[1:])
|
||||
else:
|
||||
get_terms = prompt()
|
||||
main(get_terms)
|
||||
43
attic/control/adder/coroadder0.py
Normal file
43
attic/control/adder/coroadder0.py
Normal file
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
Closing a generator raises ``GeneratorExit`` at the pending ``yield``
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(10)
|
||||
10
|
||||
>>> adder.send(20)
|
||||
30
|
||||
>>> adder.send(30)
|
||||
60
|
||||
>>> adder.close()
|
||||
-> total: 60 terms: 3 average: 20.0
|
||||
|
||||
|
||||
Other exceptions propagate to the caller:
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(10)
|
||||
10
|
||||
>>> adder.send('spam')
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
|
||||
|
||||
|
||||
"""
|
||||
|
||||
def adder_coro(initial=0):
|
||||
total = initial
|
||||
count = 0
|
||||
try:
|
||||
while True:
|
||||
term = yield total
|
||||
total += term
|
||||
count += 1
|
||||
except GeneratorExit:
|
||||
average = total / count
|
||||
msg = '-> total: {} terms: {} average: {}'
|
||||
print(msg.format(total, count, average))
|
||||
96
attic/control/adder/coroadder_deco.py
Normal file
96
attic/control/adder/coroadder_deco.py
Normal file
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(10)
|
||||
10
|
||||
>>> adder.send(20)
|
||||
30
|
||||
>>> adder.send(30)
|
||||
60
|
||||
>>> try:
|
||||
... next(adder)
|
||||
... except StopIteration as exc:
|
||||
... result = exc.value
|
||||
...
|
||||
>>> result
|
||||
Result(sum=60, terms=3, average=20.0)
|
||||
|
||||
|
||||
Closing a coroutine:
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(1)
|
||||
1
|
||||
>>> adder.send(10)
|
||||
11
|
||||
>>> adder.close()
|
||||
>>> try:
|
||||
... next(adder)
|
||||
... except StopIteration as exc:
|
||||
... exc.value is None
|
||||
...
|
||||
True
|
||||
|
||||
"""
|
||||
|
||||
import sys
|
||||
import collections
|
||||
|
||||
|
||||
def coroutine(func):
|
||||
def primed_coroutine(*args, **kwargs):
|
||||
coro = func(*args, **kwargs)
|
||||
next(coro)
|
||||
return coro
|
||||
return primed_coroutine
|
||||
|
||||
|
||||
Result = collections.namedtuple('Result', 'sum terms average')
|
||||
|
||||
|
||||
@coroutine
|
||||
def adder_coro(initial=0):
|
||||
total = initial
|
||||
num_terms = 0
|
||||
while True:
|
||||
try:
|
||||
term = yield total
|
||||
except GeneratorExit:
|
||||
break
|
||||
if term is None:
|
||||
break
|
||||
total += term
|
||||
num_terms += 1
|
||||
return Result(total, num_terms, total/num_terms)
|
||||
|
||||
|
||||
def prompt():
|
||||
while True:
|
||||
try:
|
||||
term = float(input('+ '))
|
||||
except ValueError:
|
||||
break
|
||||
yield term
|
||||
|
||||
|
||||
def main(get_terms):
|
||||
adder = adder_coro()
|
||||
for term in get_terms:
|
||||
adder.send(term)
|
||||
try:
|
||||
adder.send(None)
|
||||
except StopIteration as exc:
|
||||
result = exc.value
|
||||
print(result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
get_terms = (float(n) for n in sys.argv[1:])
|
||||
else:
|
||||
get_terms = prompt()
|
||||
main(get_terms)
|
||||
39
attic/control/adder/soma.py
Normal file
39
attic/control/adder/soma.py
Normal file
@@ -0,0 +1,39 @@
|
||||
|
||||
if 'raw_input' in dir(__builtins__):
|
||||
input = raw_input # para funcionar com Python 2
|
||||
|
||||
def ler_num():
|
||||
num = input('+: ')
|
||||
try:
|
||||
num = float(num)
|
||||
except ValueError:
|
||||
return 0
|
||||
return num
|
||||
|
||||
def somadora():
|
||||
qt_parcelas = 0
|
||||
total = 0
|
||||
try:
|
||||
while True:
|
||||
parcela = yield
|
||||
qt_parcelas += 1
|
||||
total += parcela
|
||||
print('parcelas: %d total: %d' % (qt_parcelas, total))
|
||||
|
||||
finally:
|
||||
print('parcelas: %d total: %d media: %d' % (qt_parcelas, total, total/qt_parcelas))
|
||||
|
||||
def main():
|
||||
coro = somadora()
|
||||
next(coro)
|
||||
while True:
|
||||
item = ler_num()
|
||||
if item:
|
||||
coro.send(item)
|
||||
else:
|
||||
print('Fechando corotina...')
|
||||
coro.close()
|
||||
break
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
47
attic/control/adder/soma_deco.py
Normal file
47
attic/control/adder/soma_deco.py
Normal file
@@ -0,0 +1,47 @@
|
||||
|
||||
if 'raw_input' in dir(__builtins__):
|
||||
input = raw_input # para funcionar com Python 2
|
||||
|
||||
def ler_parcela():
|
||||
parcela = input('+: ')
|
||||
try:
|
||||
parcela = float(parcela)
|
||||
except ValueError:
|
||||
return 0
|
||||
return parcela
|
||||
|
||||
# decorator
|
||||
def coro(func):
|
||||
def start(*args, **kwargs):
|
||||
g = func(*args, **kwargs)
|
||||
next(g)
|
||||
return g
|
||||
return start
|
||||
|
||||
@coro
|
||||
def somadora():
|
||||
qt_parcelas = 0
|
||||
total = 0
|
||||
try:
|
||||
while True:
|
||||
parcela = yield
|
||||
qt_parcelas += 1
|
||||
total += parcela
|
||||
|
||||
print('parcelas: %d total: %d' % (qt_parcelas, total))
|
||||
finally:
|
||||
print('parcelas: %d total: %d media: %d' % (qt_parcelas, total, total/qt_parcelas))
|
||||
|
||||
def main():
|
||||
coro = somadora()
|
||||
while True:
|
||||
parcela = ler_parcela()
|
||||
if parcela:
|
||||
coro.send(parcela)
|
||||
else:
|
||||
print('Fechando corotina...')
|
||||
coro.close()
|
||||
break
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
47
attic/control/adder/yetanother.py
Normal file
47
attic/control/adder/yetanother.py
Normal file
@@ -0,0 +1,47 @@
|
||||
import sys
|
||||
import collections
|
||||
|
||||
Result = collections.namedtuple('Result', 'total average')
|
||||
|
||||
def adder():
|
||||
total = 0
|
||||
count = 0
|
||||
while True:
|
||||
term = yield
|
||||
try:
|
||||
term = float(term)
|
||||
except (ValueError, TypeError):
|
||||
break
|
||||
else:
|
||||
total += term
|
||||
count += 1
|
||||
return Result(total, total/count)
|
||||
|
||||
def process_args(coro, args):
|
||||
for arg in args:
|
||||
coro.send(arg)
|
||||
try:
|
||||
next(coro)
|
||||
except StopIteration as exc:
|
||||
return exc.value
|
||||
|
||||
|
||||
def prompt(coro):
|
||||
while True:
|
||||
term = input('+> ')
|
||||
try:
|
||||
coro.send(term)
|
||||
except StopIteration as exc:
|
||||
return exc.value
|
||||
|
||||
|
||||
def main():
|
||||
coro = adder()
|
||||
next(coro) # prime it
|
||||
if len(sys.argv) > 1:
|
||||
res = process_args(coro, sys.argv[1:])
|
||||
else:
|
||||
res = prompt(coro)
|
||||
print(res)
|
||||
|
||||
main()
|
||||
42
attic/control/adder/yield_from_input.py
Normal file
42
attic/control/adder/yield_from_input.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import sys
|
||||
|
||||
|
||||
def ask():
|
||||
prompt = '>'
|
||||
while True:
|
||||
response = input(prompt)
|
||||
if not response:
|
||||
return 0
|
||||
yield response
|
||||
|
||||
|
||||
def parse_args():
|
||||
yield from iter(sys.argv[1:])
|
||||
|
||||
|
||||
def fetch(producer):
|
||||
gen = producer()
|
||||
next(gen)
|
||||
yield from gen
|
||||
|
||||
|
||||
def main(args):
|
||||
if args:
|
||||
producer = parse_args
|
||||
else:
|
||||
producer = ask
|
||||
|
||||
total = 0
|
||||
count = 0
|
||||
gen = fetch(producer())
|
||||
while True:
|
||||
term = yield from gen
|
||||
term = float(term)
|
||||
total += term
|
||||
count += 1
|
||||
average = total / count
|
||||
print('total: {} average: {}'.format(total, average))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1:])
|
||||
13
attic/control/coro_demo.rst
Normal file
13
attic/control/coro_demo.rst
Normal file
@@ -0,0 +1,13 @@
|
||||
>>> def coroutine():
|
||||
... print('coroutine started')
|
||||
... x = yield
|
||||
... print('coroutine received: {!r}'.format(x))
|
||||
...
|
||||
>>> coro = coroutine()
|
||||
>>> next(coro)
|
||||
coroutine started
|
||||
>>> coro.send(42)
|
||||
coroutine received: 42
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
StopIteration
|
||||
13
attic/control/coro_simple_demo.rst
Normal file
13
attic/control/coro_simple_demo.rst
Normal file
@@ -0,0 +1,13 @@
|
||||
>>> def coroutine():
|
||||
... print('coroutine started')
|
||||
... x = yield
|
||||
... print('coroutine received: {!r}'.format(x))
|
||||
...
|
||||
>>> coro = coroutine()
|
||||
>>> next(coro)
|
||||
coroutine started
|
||||
>>> coro.send(42)
|
||||
coroutine received: 42
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
StopIteration
|
||||
45
attic/control/coroaverager.py
Normal file
45
attic/control/coroaverager.py
Normal file
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
Closing a generator raises ``GeneratorExit`` at the pending ``yield``
|
||||
|
||||
>>> coro_avg = averager()
|
||||
>>> next(coro_avg)
|
||||
0.0
|
||||
>>> coro_avg.send(10)
|
||||
10.0
|
||||
>>> coro_avg.send(20)
|
||||
15.0
|
||||
>>> coro_avg.send(30)
|
||||
20.0
|
||||
>>> coro_avg.close()
|
||||
-> total: 60.0 average: 20.0 terms: 3
|
||||
|
||||
|
||||
Other exceptions propagate to the caller:
|
||||
|
||||
>>> coro_avg = averager()
|
||||
>>> next(coro_avg)
|
||||
0.0
|
||||
>>> coro_avg.send(10)
|
||||
10.0
|
||||
>>> coro_avg.send('spam')
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: unsupported operand type(s) for +=: 'float' and 'str'
|
||||
|
||||
|
||||
"""
|
||||
|
||||
# BEGIN CORO_AVERAGER
|
||||
def averager():
|
||||
total = average = 0.0
|
||||
count = 0
|
||||
try:
|
||||
while True:
|
||||
term = yield average
|
||||
total += term
|
||||
count += 1
|
||||
average = total/count
|
||||
except GeneratorExit:
|
||||
msg = '-> total: {} average: {} terms: {}'
|
||||
print(msg.format(total, average, count))
|
||||
# END CORO_AVERAGER
|
||||
69
attic/control/countdown_yf.py
Normal file
69
attic/control/countdown_yf.py
Normal file
@@ -0,0 +1,69 @@
|
||||
from time import sleep
|
||||
|
||||
def countdown(n):
|
||||
while n:
|
||||
print('\tn ->', n)
|
||||
yield n
|
||||
n -= 1
|
||||
sleep(1)
|
||||
|
||||
def foo():
|
||||
for i in range(6, 3, -1):
|
||||
yield i
|
||||
yield from countdown(3)
|
||||
|
||||
#for j in foo():
|
||||
# print('j ->', j)
|
||||
|
||||
|
||||
def squares(n):
|
||||
yield from [i for i in range(n)]
|
||||
yield from [i*i for i in range(n)]
|
||||
|
||||
def squares_stupid(n):
|
||||
for i in range(n):
|
||||
yield i
|
||||
|
||||
for i in range(n):
|
||||
yield i*i
|
||||
|
||||
#for s in squares(10):
|
||||
# print(s)
|
||||
|
||||
|
||||
def tokenize():
|
||||
while True:
|
||||
source = input('> ')
|
||||
try:
|
||||
obj = eval(source)
|
||||
except BaseException:
|
||||
print('*crash*')
|
||||
return
|
||||
try:
|
||||
it = iter(obj)
|
||||
except TypeError:
|
||||
yield obj
|
||||
return
|
||||
else:
|
||||
yield from it
|
||||
|
||||
#g = tokenize()
|
||||
|
||||
#for res in g:
|
||||
# print(res)
|
||||
|
||||
|
||||
from concurrent.futures import Future
|
||||
|
||||
def f():
|
||||
f = future()
|
||||
|
||||
def foo(fut):
|
||||
print(fut, fut.result())
|
||||
f = Future()
|
||||
f.add_done_callback(foo)
|
||||
f.set_result(42)
|
||||
|
||||
|
||||
|
||||
|
||||
24
attic/control/demo_coro.py
Normal file
24
attic/control/demo_coro.py
Normal file
@@ -0,0 +1,24 @@
|
||||
>>> def coro():
|
||||
... print 'iniciando corotina...'
|
||||
... while True:
|
||||
... x = yield
|
||||
... print 'recebido: ', x
|
||||
... if x == -1: break
|
||||
... print 'terminando corotina.'
|
||||
...
|
||||
>>> c = coro()
|
||||
>>> next(c)
|
||||
iniciando corotina...
|
||||
>>> c.send(7)
|
||||
recebido: 7
|
||||
>>> c.send(3)
|
||||
recebido: 3
|
||||
>>> c.send(10)
|
||||
recebido: 10
|
||||
>>> c.send(-1)
|
||||
recebido: -1
|
||||
terminando corotina.
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
StopIteration
|
||||
>>>
|
||||
25
attic/control/exemplo0.py
Normal file
25
attic/control/exemplo0.py
Normal file
@@ -0,0 +1,25 @@
|
||||
def corrotina():
|
||||
print('\t(corrotina) inciciando...')
|
||||
x = yield
|
||||
print('\t(corrotina) recebeu x: %r' % x)
|
||||
y = yield
|
||||
print('\t(corrotina) recebeu y: %r' % y)
|
||||
print('\t(corrotina) terminando.')
|
||||
|
||||
|
||||
def principal():
|
||||
print('(principal) iniciando...')
|
||||
co = corrotina()
|
||||
print('(principal) invocando next(co)...')
|
||||
next(co)
|
||||
print('(principal) invocando co.send(88)...')
|
||||
co.send(88)
|
||||
try:
|
||||
print('(principal) invocando co.send(99)...')
|
||||
co.send(99)
|
||||
# o print a seguir nunca vai acontecer
|
||||
print('(principal) invocado co.send(99)')
|
||||
except StopIteration:
|
||||
print('(principal) a corotina nao tem mais valores a produzir')
|
||||
|
||||
principal()
|
||||
27
attic/control/exemplo1.py
Normal file
27
attic/control/exemplo1.py
Normal file
@@ -0,0 +1,27 @@
|
||||
def corrotina():
|
||||
print('\t(corrotina) inciciando...')
|
||||
x = yield 1
|
||||
print('\t(corrotina) recebeu x: %r' % x)
|
||||
y = yield 2
|
||||
print('\t(corrotina) recebeu y: %r' % y)
|
||||
print('\t(corrotina) terminando.')
|
||||
|
||||
|
||||
def principal():
|
||||
print('(principal) iniciando...')
|
||||
co = corrotina()
|
||||
print('(principal) invocando next(co)...')
|
||||
res = next(co)
|
||||
print('(principal) produzido por next(co): %r' % res)
|
||||
print('(principal) invocando co.send(88)...')
|
||||
res2 = co.send(88)
|
||||
print('(principal) produzido por co.send(88): %r' % res2)
|
||||
try:
|
||||
print('(principal) invocando co.send(99)...')
|
||||
res3 = co.send(99)
|
||||
# o print a seguir nunca vai acontecer
|
||||
print('(principal) produzido por co.send(99): %r' % res3)
|
||||
except StopIteration:
|
||||
print('(principal) a corotina nao tem mais valores a produzir')
|
||||
principal()
|
||||
|
||||
21
attic/control/flatten.py
Normal file
21
attic/control/flatten.py
Normal file
@@ -0,0 +1,21 @@
|
||||
"""
|
||||
|
||||
>>> items = [1, 2, [3, 4, [5, 6], 7], 8]
|
||||
>>> flatten(items)
|
||||
<generator object flatten at 0x73bd9c>
|
||||
>>> list(flatten(items))
|
||||
[1, 2, 3, 4, 5, 6, 7, 8]
|
||||
>>> mixed_bag = [1, 'spam', 2, [3, 'eggs', 4], {'x': 1, 'y': 2}]
|
||||
>>> list(flatten(mixed_bag))
|
||||
[1, 'spam', 2, 3, 'eggs', 4, 'y', 'x']
|
||||
"""
|
||||
|
||||
|
||||
from collections import Iterable
|
||||
|
||||
def flatten(items):
|
||||
for x in items:
|
||||
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
|
||||
yield from flatten(x)
|
||||
else:
|
||||
yield x
|
||||
26
attic/control/guido/guido0.py
Normal file
26
attic/control/guido/guido0.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
Exemplo adaptado da mensagem do Guido van Rossum em:
|
||||
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
|
||||
http://bit.ly/yieldfrom
|
||||
|
||||
>>> principal(ger1())
|
||||
OK
|
||||
42
|
||||
|
||||
Visualização no PythonTutor: http://goo.gl/FQWq2F
|
||||
|
||||
"""
|
||||
|
||||
def ger1():
|
||||
val = yield 'OK'
|
||||
print(val)
|
||||
yield # para evitar o StopIteration
|
||||
|
||||
def principal(g):
|
||||
print(next(g))
|
||||
g.send(42)
|
||||
|
||||
|
||||
# auto-teste
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
29
attic/control/guido/guido1.py
Normal file
29
attic/control/guido/guido1.py
Normal file
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
Exemplo adaptado da mensagem do Guido van Rossum em:
|
||||
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
|
||||
http://bit.ly/yieldfrom
|
||||
|
||||
>>> principal(ger2())
|
||||
OK
|
||||
42
|
||||
|
||||
Visualização no PythonTutor: http://goo.gl/pWrlkm
|
||||
|
||||
"""
|
||||
|
||||
def ger1():
|
||||
val = yield 'OK'
|
||||
print(val)
|
||||
yield # para evitar o StopIteration
|
||||
|
||||
def ger2():
|
||||
yield from ger1()
|
||||
|
||||
def principal(g):
|
||||
print(next(g))
|
||||
g.send(42)
|
||||
|
||||
|
||||
# auto-teste
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
30
attic/control/guido/guido1b.py
Normal file
30
attic/control/guido/guido1b.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
Exemplo adaptado da mensagem do Guido van Rossum em:
|
||||
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
|
||||
http://bit.ly/yieldfrom
|
||||
|
||||
>>> principal(ger2())
|
||||
OK
|
||||
None
|
||||
|
||||
Visualização no PythonTutor: http://goo.gl/61CUcA
|
||||
|
||||
"""
|
||||
|
||||
def ger1():
|
||||
val = yield 'OK'
|
||||
print(val)
|
||||
yield # para evitar o StopIteration
|
||||
|
||||
def ger2():
|
||||
for i in ger1():
|
||||
yield i
|
||||
|
||||
def principal(g):
|
||||
print(next(g))
|
||||
g.send(42)
|
||||
|
||||
|
||||
# auto-teste
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
31
attic/control/guido/guido2.py
Normal file
31
attic/control/guido/guido2.py
Normal file
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
Exemplo adaptado da mensagem do Guido van Rossum em:
|
||||
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
|
||||
http://bit.ly/yieldfrom
|
||||
|
||||
>>> principal_susto(ger1())
|
||||
OK
|
||||
Bu!
|
||||
|
||||
Visualização no PythonTutor: http://goo.gl/m6p2Bc
|
||||
|
||||
"""
|
||||
|
||||
def ger1():
|
||||
try:
|
||||
val = yield 'OK'
|
||||
except RuntimeError as exc:
|
||||
print(exc)
|
||||
else:
|
||||
print(val)
|
||||
yield # para evitar o StopIteration
|
||||
|
||||
|
||||
def principal_susto(g):
|
||||
print(next(g))
|
||||
g.throw(RuntimeError('Bu!'))
|
||||
|
||||
|
||||
# auto-teste
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
35
attic/control/guido/guido3.py
Normal file
35
attic/control/guido/guido3.py
Normal file
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
Exemplo adaptado da mensagem do Guido van Rossum em:
|
||||
https://groups.google.com/forum/#!msg/python-tulip/bmphRrryuFk/aB45sEJUomYJ
|
||||
http://bit.ly/yieldfrom
|
||||
|
||||
>>> principal_susto(ger2())
|
||||
OK
|
||||
Bu!
|
||||
|
||||
Visualização no PythonTutor: http://goo.gl/QXzQHS
|
||||
|
||||
"""
|
||||
|
||||
def ger1():
|
||||
try:
|
||||
val = yield 'OK'
|
||||
except RuntimeError as exc:
|
||||
print(exc)
|
||||
else:
|
||||
print(val)
|
||||
yield # para evitar o StopIteration
|
||||
|
||||
|
||||
def ger2():
|
||||
yield from ger1()
|
||||
|
||||
|
||||
def principal_susto(g):
|
||||
print(next(g))
|
||||
g.throw(RuntimeError('Bu!'))
|
||||
|
||||
|
||||
# auto-teste
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
20
attic/control/http_cli0.py
Normal file
20
attic/control/http_cli0.py
Normal file
@@ -0,0 +1,20 @@
|
||||
# adaptado de:
|
||||
# https://github.com/feihong/tulip-talk/blob/master/examples/2-tulip-download.py
|
||||
|
||||
import asyncio
|
||||
import aiohttp
|
||||
|
||||
@asyncio.coroutine
|
||||
def download(url):
|
||||
response = yield from aiohttp.request('GET', url)
|
||||
for k, v in response.items():
|
||||
print('{}: {}'.format(k, v[:80]))
|
||||
|
||||
data = yield from response.read()
|
||||
print('\nReceived {} bytes.\n'.format(len(data)))
|
||||
|
||||
if __name__ == '__main__':
|
||||
loop = asyncio.get_event_loop()
|
||||
url = 'https://www.cia.gov/library/publications/the-world-factbook/geos/br.html'
|
||||
coroutine = download(url)
|
||||
loop.run_until_complete(coroutine)
|
||||
5
attic/control/kwcombos.py
Normal file
5
attic/control/kwcombos.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from keyword import kwlist
|
||||
from itertools import combinations
|
||||
|
||||
for combo in combinations(kwlist, 2):
|
||||
print(*combo)
|
||||
14
attic/iterables/aritprog_v4.py
Normal file
14
attic/iterables/aritprog_v4.py
Normal file
@@ -0,0 +1,14 @@
|
||||
# BEGIN ARITPROG_ITERTOOLS
|
||||
import itertools
|
||||
|
||||
|
||||
def aritprog_gen(begin, step, end=None):
|
||||
if end is not None and begin >= end:
|
||||
return
|
||||
yield type(begin + step)(begin)
|
||||
tail_gen = itertools.count(begin+step, step)
|
||||
if end is not None:
|
||||
tail_gen = itertools.takewhile(lambda n: n < end, tail_gen)
|
||||
for x in tail_gen:
|
||||
yield x
|
||||
# END ARITPROG_ITERTOOLS
|
||||
13
attic/iterables/aritprog_v5.py
Normal file
13
attic/iterables/aritprog_v5.py
Normal file
@@ -0,0 +1,13 @@
|
||||
# BEGIN ARITPROG_ITERTOOLS
|
||||
import itertools
|
||||
|
||||
|
||||
def aritprog_gen(begin, step, end=None):
|
||||
if end is not None and begin >= end:
|
||||
return
|
||||
yield type(begin + step)(begin)
|
||||
tail_gen = itertools.count(begin+step, step)
|
||||
if end is not None:
|
||||
tail_gen = itertools.takewhile(lambda n: n < end, tail_gen)
|
||||
yield from tail_gen
|
||||
# END ARITPROG_ITERTOOLS
|
||||
Reference in New Issue
Block a user