Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Концепция сопрограмм
Александр Мокров
Асинхронность
«Подпрограммы — это частные случаи более общих программных
компонентов, называемых сопрограммами. В противоположность
неси...
Подпрограммы
Сопрограммы
Coroutines
Disclaimers
Coroutines — одна из наиболее неясных
особенностей Python
Асинхронность и конкурентность — одни из
наиболее сл...
Итераторы
Итерируемые объекты (iterables) - объект,
который реализует метод __iter__(),
возвращающий итератор.
Итератор — объект, ре...
class Letter:
def __init__(self):
self.current = 'a'
def __next__(self):
if self.current > 'd':
raise StopIteration
result...
>>> iletter = Letter()
>>> letter = iter(iletter)
>>> letter.__next__()
'a'
>>> letter.__next__()
'b'
>>> next(letter)
'c'...
For Statements
letter = Letter()
>>> i = letter.__iter__()
>>> try:
while True:
item = i.__next__()
print(item)
except Sto...
PEP 255 -- Simple Generators
Authors:
Neil Schemenauer <nas at arctrix.com>,
Tim Peters <tim.peters at gmail.com>,
Magnus ...
>>> def letters_generator():
current = 'a'
while current <= 'd':
yield current
current = chr(ord(current)+1)
>>> for lette...
def countdown(n):
print("Counting down from", n)
while n > 0:
yield n
n -= 1
>>> x = countdown(10)
>>> x
<generator object...
Генераторы
Прострой способ создания итераторов
,Простой синтаксис добавлено только
yieldключевое слово
Запоминаются состоя...
PEP 342 Coroutine via Enhanced Generators
Authors: Guido van Rossum, Phillip J. Eby
Created: 10-May-2005
Python 2.5
PEP 28...
Что добавилось
1. (yield) statement:
value = (yield)
2. send()
3. throw()
4. close()
5. Вызов close() сборщиком мусора
6. ...
>>> def match(pattern):
print('Ищем ' + pattern)
try:
while True:
s = (yield)
if pattern in s:
print(s)
except GeneratorEx...
Produce, Filter, and Consume
Producer
def read(text, next_coroutine):
for line in text.split():
next_coroutine.send(line)
next_coroutine.close()
Filter
def match_filter(pattern, next_coroutine):
print('Looking for ' + pattern)
try:
while True:
s = (yield)
if pattern ...
Consumer
def print_consumer():
print('Preparing to print')
try:
while True:
line = (yield)
print(line)
except GeneratorExi...
>>> printer = print_consumer()
>>> printer.__next__()
Preparing to print
>>> matcher = match_filter('pend', printer)
>>> m...
PEP 380 Syntax for Delegating to a Subgenerator
Authors: Gregory Ewing
Created: 13-Feb-2009
Python 3.3
Новый оператор
RESULT = yield from EXPR
Теперь вместо
for v in g:
yield v
Можно писать
yield from g
def writer():
while True:
w = (yield)
print('>> ', w)
def writer_wrapper(coro):
pass
w = writer()
wrap = writer_wrapper(w)...
def writer_wrapper(coro):
coro.send(None) # prime the coro
while True:
try:
x = (yield) # Capture the value that's sent
co...
class SpamException(Exception):
pass
def writer():
while True:
try:
w = (yield)
except SpamException:
print('***')
else:
p...
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
if i == 'spam...
def writer_wrapper(coro):
"""Works. Manually catches exceptions and throws them"""
coro.send(None) # prime the coro
while ...
def writer_wrapper(coro):
yield from coro
Пару слов об asyncio и сопрограммах в нем
PEP 0492 -- Coroutines with async and await
syntax
Authors: Yury Selivanov
Created: 09-Apr-2015
Python 3.5
New Coroutine Declaration Syntax
async def read_data(db):
pass
Await Expression
async def read_data(db):
data = await db.fetch('SELECT ...')
...
Asynchronous Context Managers and "async
with"
class AsyncContextManager:
async def __aenter__(self):
await log('entering ...
async def commit(session, data):
...
async with session.transaction():
...
await session.update(data)
…
Код, требующий бло...
Asynchronous Iterators and "async for"
class Cursor:
def __init__(self):
self.buffer = collections.deque()
async def _pref...
https://www.python.org/dev/peps
http://wla.berkeley.edu/~cs61a/fa11/lectures/streams.
http://www.dabeaz.com/coroutines/
Сс...
Спасибо!
Coroutines
Coroutines
Prochain SlideShare
Chargement dans…5
×

Coroutines

380 vues

Publié le

Coroutines concept

Publié dans : Logiciels
  • DOWNLOAD FULL BOOKS INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL PDF EBOOK here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL EPUB Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL doc Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL PDF EBOOK here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL EPUB Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL doc Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • Soyez le premier à aimer ceci

Coroutines

  1. 1. Концепция сопрограмм Александр Мокров
  2. 2. Асинхронность
  3. 3. «Подпрограммы — это частные случаи более общих программных компонентов, называемых сопрограммами. В противоположность несимметричной связи между главной программой и подпрограммой, между сопрограммами, которые вызывают одна другую, существует полная симметрия.» «Искусство программирования» Д. Кнут «A coroutine is similar to a procedure and a generator is similar to a function. The principle difference between these program units and procedures/functions is that the call/return mechanism is different. Coroutines are especially useful for multiplayer games and other program flow where sections of code "take turns" executing. Generators, as their name implies, are useful for generating a sequence of values; in many respects generators are quite similar to HLA’s iterators without all the restrictions of the iterators » «The Art of Assembly Language» by Randall Hyde
  4. 4. Подпрограммы
  5. 5. Сопрограммы
  6. 6. Coroutines
  7. 7. Disclaimers Coroutines — одна из наиболее неясных особенностей Python Асинхронность и конкурентность — одни из наиболее сложных тем в computer science Основной фундамент заложен в 60-80 годы, но работа в этом направлении была закончена в пользу других альтернатив (threads, continuations...)
  8. 8. Итераторы
  9. 9. Итерируемые объекты (iterables) - объект, который реализует метод __iter__(), возвращающий итератор. Итератор — объект, реализующие метод __next__()
  10. 10. class Letter: def __init__(self): self.current = 'a' def __next__(self): if self.current > 'd': raise StopIteration result = self.current self.current = chr(ord(result)+1) return result def __iter__(self): return self
  11. 11. >>> iletter = Letter() >>> letter = iter(iletter) >>> letter.__next__() 'a' >>> letter.__next__() 'b' >>> next(letter) 'c' >>> next(letter) 'd' >>> next(letter) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "letter.py", line 7, in __next__ raise StopIteration StopIteration >>> letter = Letter() >>> for l in letter: ... print(l) ... a b c d >>> sum(letter) 0
  12. 12. For Statements letter = Letter() >>> i = letter.__iter__() >>> try: while True: item = i.__next__() print(item) except StopIteration: pass a b c d
  13. 13. PEP 255 -- Simple Generators Authors: Neil Schemenauer <nas at arctrix.com>, Tim Peters <tim.peters at gmail.com>, Magnus Lie Hetland <magnus at hetland.org> Created: 18-May-2001 Python 2.2
  14. 14. >>> def letters_generator(): current = 'a' while current <= 'd': yield current current = chr(ord(current)+1) >>> for letter in letters_generator(): print(letter) a b c d
  15. 15. def countdown(n): print("Counting down from", n) while n > 0: yield n n -= 1 >>> x = countdown(10) >>> x <generator object countdown at 0x7fe8f9cd5318> >>> next(x) Counting down from 10 10 >>>
  16. 16. Генераторы Прострой способ создания итераторов ,Простой синтаксис добавлено только yieldключевое слово Запоминаются состояния между вызовами IconСтащили идею из
  17. 17. PEP 342 Coroutine via Enhanced Generators Authors: Guido van Rossum, Phillip J. Eby Created: 10-May-2005 Python 2.5 PEP 288, Generators Attributes and Exceptions (Raymond Hettinger) PEP 325, Resource-Release Support for Generators (Samuele Pedroni)
  18. 18. Что добавилось 1. (yield) statement: value = (yield) 2. send() 3. throw() 4. close() 5. Вызов close() сборщиком мусора 6. Разрешено использование yield внутри try/finally блоков
  19. 19. >>> def match(pattern): print('Ищем ' + pattern) try: while True: s = (yield) if pattern in s: print(s) except GeneratorExit: print("=== Done ===") >>> m = match("runnts") >>> m.__next__() Ищем runnts >>> m.send("А про rannts - все очень просто.") А про rannts - все очень просто. >>> m.send("Две n - географическая привязка") >>> m.send("rant - тирады, пустословие, помпезные речи, бахвальство, декламация и шумная проповедь") >>> m.close() === Done ===
  20. 20. Produce, Filter, and Consume
  21. 21. Producer def read(text, next_coroutine): for line in text.split(): next_coroutine.send(line) next_coroutine.close()
  22. 22. Filter def match_filter(pattern, next_coroutine): print('Looking for ' + pattern) try: while True: s = (yield) if pattern in s: next_coroutine.send(s) except GeneratorExit: next_coroutine.close()
  23. 23. Consumer def print_consumer(): print('Preparing to print') try: while True: line = (yield) print(line) except GeneratorExit: print("=== Done ===")
  24. 24. >>> printer = print_consumer() >>> printer.__next__() Preparing to print >>> matcher = match_filter('pend', printer) >>> matcher.__next__() Looking for pend >>> read(text, matcher) spending pending === Done ===
  25. 25. PEP 380 Syntax for Delegating to a Subgenerator Authors: Gregory Ewing Created: 13-Feb-2009 Python 3.3
  26. 26. Новый оператор RESULT = yield from EXPR Теперь вместо for v in g: yield v Можно писать yield from g
  27. 27. def writer(): while True: w = (yield) print('>> ', w) def writer_wrapper(coro): pass w = writer() wrap = writer_wrapper(w) wrap.send(None) for i in range(4): wrap.send(i) # Expected result >> 0 >> 1 >> 2 >> 3
  28. 28. def writer_wrapper(coro): coro.send(None) # prime the coro while True: try: x = (yield) # Capture the value that's sent coro.send(x) # and pass it to the writer except StopIteration: pass или def writer_wrapper(coro): yield from coro
  29. 29. class SpamException(Exception): pass def writer(): while True: try: w = (yield) except SpamException: print('***') else: print('>> ', w)
  30. 30. w = writer() wrap = writer_wrapper(w) wrap.send(None) # "prime" the coroutine for i in [0, 1, 2, 'spam', 4]: if i == 'spam': wrap.throw(SpamException) else: wrap.send(i) # Expected Result >> 0 >> 1 >> 2 *** >> 4 # Actual Result >> 0 >> 1 >> 2 Traceback (most recent call last): ... redacted ... File ... in writer_wrapper x = (yield) __main__.SpamException
  31. 31. def writer_wrapper(coro): """Works. Manually catches exceptions and throws them""" coro.send(None) # prime the coro while True: try: try: x = (yield) except Exception as e: # This catches the SpamException coro.throw(e) else: coro.send(x) except StopIteration: pass # Result >> 0 >> 1 >> 2 *** >> 4
  32. 32. def writer_wrapper(coro): yield from coro
  33. 33. Пару слов об asyncio и сопрограммах в нем
  34. 34. PEP 0492 -- Coroutines with async and await syntax Authors: Yury Selivanov Created: 09-Apr-2015 Python 3.5
  35. 35. New Coroutine Declaration Syntax async def read_data(db): pass
  36. 36. Await Expression async def read_data(db): data = await db.fetch('SELECT ...') ...
  37. 37. Asynchronous Context Managers and "async with" class AsyncContextManager: async def __aenter__(self): await log('entering context') async def __aexit__(self, exc_type, exc, tb): await log('exiting context')
  38. 38. async def commit(session, data): ... async with session.transaction(): ... await session.update(data) … Код, требующий блокировки: async with lock: … вместо: with (yield from lock): ...
  39. 39. Asynchronous Iterators and "async for" class Cursor: def __init__(self): self.buffer = collections.deque() async def _prefetch(self): ... async def __aiter__(self): return self async def __anext__(self): if not self.buffer: self.buffer = await self._prefetch() if not self.buffer: raise StopAsyncIteration return self.buffer.popleft() async for row in Cursor(): print(row)
  40. 40. https://www.python.org/dev/peps http://wla.berkeley.edu/~cs61a/fa11/lectures/streams. http://www.dabeaz.com/coroutines/ Ссылки
  41. 41. Спасибо!

×