SlideShare a Scribd company logo
pen4education
Seu Primeiro Loop com AsyncIO
Carlos Maniero
Desenvolvedor Python na Loja Integrada
pen4education
Não tenha medo
pen4education
Motivacional
“É necessário a disciplina de um super humano
para escrever código legível baseado em
callbacks, se você não acredita em mim, olhe
qualquer pedaço de código javascript.”
pen4education
Motivacional
“É necessário a disciplina de um super humano
para escrever código legível baseado em
callbacks, se você não acredita em mim, olhe
qualquer pedaço de código javascript.”
Guido Van Rossum
pen4education
Motivacional
https://www.python.org/~guido/
pen4education
Polêmica
“Threads em Python são
excelentes em fazer nada.”
David Beazley
http://www.dabeaz.com/
pen4education
Hello World
import asyncio
async def hello_world():
print("Hello World!")
loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
loop.close()
Python 3.5
pen4education
Hello World
import asyncio
@asyncio.coroutine
def hello_world():
print("Hello World!")
loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
loop.close()
Python 3.4
pen4education
Py 3.4 vs Py 3.5
Python 3.4 Python 3.5
async def hello_world():
@asyncio.coroutine
def hello_world():
await x()yield from x()
pen4education
Event Loop
O Event Loop é o dispositivo central de execução.
● Registra, executar e cancela tarefas
● Cria servidores e clients para vários tipos de
comunicação (ex: sockets)
● Delega processos pesados a um executor. (ex:
ThreadPoolExecutor)
pen4education
Coroutine
Coroutine utiliza do statement yield do Python para
controlar a execução do código de uma função.
Sendo possível bloquear, continuar e realizar a
comunicação sem a necessidade de criação de
funções de callback.
pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
1 None
pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
1 10
pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
2 30
pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
2 30
pen4education
Coroutine
def media():
n = 1
total = yield
while True:
total += (yield total / n)
n += 1
coro = media()
next(coro)
print(coro.send(10))
>>> 10.0
print(coro.send(20))
>>> 15.0
n total
2 30
pen4education
Task/Future
● Responsável pelo controle de execução de uma
corroutine.
● Contém importantes métodos como done(),
result() e cancel().
● Uma Task só é gerada pelo asyncio, utilizando
o asyncio.ensure_future() ou o loop.create_task
().
pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading()) # Cria task
content = await run_very_long_task() # Espera por retorno
loading_task.cancel() # Cancela execução da task
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
Task/Future
pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading()) # Cria task
content = await run_very_long_task() # Espera por retorno
loading_task.cancel() # Cancela execução da task
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
Task/Future
Loading .
Loading ..
Loading ...
Loading ....
Loading .....
Loading ......
The result is 42
pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading())
content = await run_very_long_task()
loading_task.cancel()
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading())
content = await run_very_long_task()
loading_task.cancel()
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
pen4education
import asyncio
async def loading():
i = 1
while True:
print('Loading ' + '.' * i)
await asyncio.sleep(0.5)
i += 1
async def run_very_long_task():
await asyncio.sleep(3)
return 42
async def supervisor():
loading_task = asyncio.ensure_future(loading())
content = await run_very_long_task()
loading_task.cancel()
print('The result is {}'.format(content))
loop = asyncio.get_event_loop()
loop.run_until_complete(supervisor())
loop.close()
pen4education
import asyncio
import time
def slow_function():
time.sleep(3)
return 42
async def test1():
slow_function()
print('Finish test1')
async def test2():
for i in range(0, 10):
print(i)
await asyncio.sleep(0.5)
print('Finish test2')
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([
test1(),
test2()
]))
Bloqueio do Loop
Finish test1
0
1
2
3
4
5
6
7
8
9
Finish test2
pen4education
import asyncio
import time
def slow_function():
time.sleep(3)
return 42
async def test1():
await loop.run_in_executor(None, slow_function)
print('Finish test1')
async def test2():
for i in range(0, 10):
print(i)
await asyncio.sleep(0.5)
print('Finish test2')
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([
test1(),
test2()
]))
Bloqueio do Loop
0
1
2
3
4
5
Finish test1
6
7
8
9
Finish test2
pen4education
O que ver a seguir?
● ThreadPoolExecutor
● aioHTTP
pen4education
Obrigado <3
github.com/carlosmaniero
youtube.com/carlosmaniero
carlosmaniero@gmail.com

More Related Content

What's hot (20)

PPTX
C++ Lambda and concurrency
명신 김
 
PDF
Any event intro
qiang
 
PDF
An (abridged) Ruby Plumber's Guide to *nix
Eleanor McHugh
 
TXT
Source Code
vijaykantsaini
 
PPT
Ch4
aamirsahito
 
ODP
Anyevent
Marian Marinov
 
PPTX
Gevent rabbit rpc
Aleksandr Mokrov
 
PDF
Node.js flow control
Simon Su
 
PDF
The Ring programming language version 1.5.3 book - Part 25 of 184
Mahmoud Samir Fayed
 
PPTX
Node child process
LearningTech
 
PDF
Cooking pies with Celery
Aleksandr Mokrov
 
PPTX
Serverless stateful
Patrick Di Loreto
 
PPTX
node.js workshop- node.js basics
Qiong Wu
 
PDF
Clojure@Nuday
Josh Glover
 
PDF
Goroutines and Channels in practice
Guilherme Garnier
 
KEY
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
Eleanor McHugh
 
PPTX
Perl: Coro asynchronous
Shmuel Fomberg
 
DOCX
Programa donde suma las filass de las dos columna y ordena el resultado de l...
Yo no soy perfecta pero soy mejor que tu
 
DOCX
Programming
naiinisakosayo
 
PPTX
Mysql5.1 character set testing
Philip Zhong
 
C++ Lambda and concurrency
명신 김
 
Any event intro
qiang
 
An (abridged) Ruby Plumber's Guide to *nix
Eleanor McHugh
 
Source Code
vijaykantsaini
 
Anyevent
Marian Marinov
 
Gevent rabbit rpc
Aleksandr Mokrov
 
Node.js flow control
Simon Su
 
The Ring programming language version 1.5.3 book - Part 25 of 184
Mahmoud Samir Fayed
 
Node child process
LearningTech
 
Cooking pies with Celery
Aleksandr Mokrov
 
Serverless stateful
Patrick Di Loreto
 
node.js workshop- node.js basics
Qiong Wu
 
Clojure@Nuday
Josh Glover
 
Goroutines and Channels in practice
Guilherme Garnier
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
Eleanor McHugh
 
Perl: Coro asynchronous
Shmuel Fomberg
 
Programa donde suma las filass de las dos columna y ordena el resultado de l...
Yo no soy perfecta pero soy mejor que tu
 
Programming
naiinisakosayo
 
Mysql5.1 character set testing
Philip Zhong
 

Similar to Seu primeiro loop com Python AsyncIO - TDC 2016 (20)

PDF
Python Async IO Horizon
Lukasz Dobrzanski
 
PPTX
Async programming and python
Chetan Giridhar
 
PDF
PyCon Canada 2019 - Introduction to Asynchronous Programming
Juti Noppornpitak
 
PDF
Webscraping with asyncio
Jose Manuel Ortega Candel
 
PPTX
Understanding concurrency
Anshul Sharma
 
PDF
Codemania101: The Present, Past and Future of Asynchronous Programming in Python
Yothin Muangsommuk
 
PDF
asyncio internals
Saúl Ibarra Corretgé
 
PDF
concurrency
Jonathan Wagoner
 
PDF
Alta performance com Python
Bruno Barbosa
 
PDF
The journey of asyncio adoption in instagram
Jimmy Lai
 
PDF
Asynchronous Python A Gentle Introduction
PyData
 
PDF
Python Coroutines, Present and Future
emptysquare
 
PPTX
Asynchronous programming with django
bangaloredjangousergroup
 
PDF
BUILDING APPS WITH ASYNCIO
Mykola Novik
 
PDF
Introduction to Python Asyncio
Nathan Van Gheem
 
PDF
Python, do you even async?
Saúl Ibarra Corretgé
 
PDF
Async Web Frameworks in Python
Ryan Johnson
 
PPT
AsyncIO To Speed Up Your Crawler
Linggar Primahastoko
 
PPTX
Python UNIT-IV Multi Threading B.Tech CSE
SrinuTelugu
 
PDF
Introduction to asyncio
Saúl Ibarra Corretgé
 
Python Async IO Horizon
Lukasz Dobrzanski
 
Async programming and python
Chetan Giridhar
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
Juti Noppornpitak
 
Webscraping with asyncio
Jose Manuel Ortega Candel
 
Understanding concurrency
Anshul Sharma
 
Codemania101: The Present, Past and Future of Asynchronous Programming in Python
Yothin Muangsommuk
 
asyncio internals
Saúl Ibarra Corretgé
 
concurrency
Jonathan Wagoner
 
Alta performance com Python
Bruno Barbosa
 
The journey of asyncio adoption in instagram
Jimmy Lai
 
Asynchronous Python A Gentle Introduction
PyData
 
Python Coroutines, Present and Future
emptysquare
 
Asynchronous programming with django
bangaloredjangousergroup
 
BUILDING APPS WITH ASYNCIO
Mykola Novik
 
Introduction to Python Asyncio
Nathan Van Gheem
 
Python, do you even async?
Saúl Ibarra Corretgé
 
Async Web Frameworks in Python
Ryan Johnson
 
AsyncIO To Speed Up Your Crawler
Linggar Primahastoko
 
Python UNIT-IV Multi Threading B.Tech CSE
SrinuTelugu
 
Introduction to asyncio
Saúl Ibarra Corretgé
 
Ad

Recently uploaded (20)

PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Import Data Form Excel to Tally Services
Tally xperts
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Ad

Seu primeiro loop com Python AsyncIO - TDC 2016

  • 1. pen4education Seu Primeiro Loop com AsyncIO Carlos Maniero Desenvolvedor Python na Loja Integrada
  • 3. pen4education Motivacional “É necessário a disciplina de um super humano para escrever código legível baseado em callbacks, se você não acredita em mim, olhe qualquer pedaço de código javascript.”
  • 4. pen4education Motivacional “É necessário a disciplina de um super humano para escrever código legível baseado em callbacks, se você não acredita em mim, olhe qualquer pedaço de código javascript.” Guido Van Rossum
  • 6. pen4education Polêmica “Threads em Python são excelentes em fazer nada.” David Beazley http://www.dabeaz.com/
  • 7. pen4education Hello World import asyncio async def hello_world(): print("Hello World!") loop = asyncio.get_event_loop() loop.run_until_complete(hello_world()) loop.close() Python 3.5
  • 8. pen4education Hello World import asyncio @asyncio.coroutine def hello_world(): print("Hello World!") loop = asyncio.get_event_loop() loop.run_until_complete(hello_world()) loop.close() Python 3.4
  • 9. pen4education Py 3.4 vs Py 3.5 Python 3.4 Python 3.5 async def hello_world(): @asyncio.coroutine def hello_world(): await x()yield from x()
  • 10. pen4education Event Loop O Event Loop é o dispositivo central de execução. ● Registra, executar e cancela tarefas ● Cria servidores e clients para vários tipos de comunicação (ex: sockets) ● Delega processos pesados a um executor. (ex: ThreadPoolExecutor)
  • 11. pen4education Coroutine Coroutine utiliza do statement yield do Python para controlar a execução do código de uma função. Sendo possível bloquear, continuar e realizar a comunicação sem a necessidade de criação de funções de callback.
  • 12. pen4education Coroutine def media(): n = 1 total = yield while True: total += (yield total / n) n += 1 coro = media() next(coro) print(coro.send(10)) >>> 10.0 print(coro.send(20)) >>> 15.0
  • 13. pen4education Coroutine def media(): n = 1 total = yield while True: total += (yield total / n) n += 1 coro = media() next(coro) print(coro.send(10)) >>> 10.0 print(coro.send(20)) >>> 15.0
  • 14. pen4education Coroutine def media(): n = 1 total = yield while True: total += (yield total / n) n += 1 coro = media() next(coro) print(coro.send(10)) >>> 10.0 print(coro.send(20)) >>> 15.0 n total 1 None
  • 15. pen4education Coroutine def media(): n = 1 total = yield while True: total += (yield total / n) n += 1 coro = media() next(coro) print(coro.send(10)) >>> 10.0 print(coro.send(20)) >>> 15.0 n total 1 10
  • 16. pen4education Coroutine def media(): n = 1 total = yield while True: total += (yield total / n) n += 1 coro = media() next(coro) print(coro.send(10)) >>> 10.0 print(coro.send(20)) >>> 15.0 n total 2 30
  • 17. pen4education Coroutine def media(): n = 1 total = yield while True: total += (yield total / n) n += 1 coro = media() next(coro) print(coro.send(10)) >>> 10.0 print(coro.send(20)) >>> 15.0 n total 2 30
  • 18. pen4education Coroutine def media(): n = 1 total = yield while True: total += (yield total / n) n += 1 coro = media() next(coro) print(coro.send(10)) >>> 10.0 print(coro.send(20)) >>> 15.0 n total 2 30
  • 19. pen4education Task/Future ● Responsável pelo controle de execução de uma corroutine. ● Contém importantes métodos como done(), result() e cancel(). ● Uma Task só é gerada pelo asyncio, utilizando o asyncio.ensure_future() ou o loop.create_task ().
  • 20. pen4education import asyncio async def loading(): i = 1 while True: print('Loading ' + '.' * i) await asyncio.sleep(0.5) i += 1 async def run_very_long_task(): await asyncio.sleep(3) return 42 async def supervisor(): loading_task = asyncio.ensure_future(loading()) # Cria task content = await run_very_long_task() # Espera por retorno loading_task.cancel() # Cancela execução da task print('The result is {}'.format(content)) loop = asyncio.get_event_loop() loop.run_until_complete(supervisor()) loop.close() Task/Future
  • 21. pen4education import asyncio async def loading(): i = 1 while True: print('Loading ' + '.' * i) await asyncio.sleep(0.5) i += 1 async def run_very_long_task(): await asyncio.sleep(3) return 42 async def supervisor(): loading_task = asyncio.ensure_future(loading()) # Cria task content = await run_very_long_task() # Espera por retorno loading_task.cancel() # Cancela execução da task print('The result is {}'.format(content)) loop = asyncio.get_event_loop() loop.run_until_complete(supervisor()) loop.close() Task/Future Loading . Loading .. Loading ... Loading .... Loading ..... Loading ...... The result is 42
  • 22. pen4education import asyncio async def loading(): i = 1 while True: print('Loading ' + '.' * i) await asyncio.sleep(0.5) i += 1 async def run_very_long_task(): await asyncio.sleep(3) return 42 async def supervisor(): loading_task = asyncio.ensure_future(loading()) content = await run_very_long_task() loading_task.cancel() print('The result is {}'.format(content)) loop = asyncio.get_event_loop() loop.run_until_complete(supervisor()) loop.close()
  • 23. pen4education import asyncio async def loading(): i = 1 while True: print('Loading ' + '.' * i) await asyncio.sleep(0.5) i += 1 async def run_very_long_task(): await asyncio.sleep(3) return 42 async def supervisor(): loading_task = asyncio.ensure_future(loading()) content = await run_very_long_task() loading_task.cancel() print('The result is {}'.format(content)) loop = asyncio.get_event_loop() loop.run_until_complete(supervisor()) loop.close()
  • 24. pen4education import asyncio async def loading(): i = 1 while True: print('Loading ' + '.' * i) await asyncio.sleep(0.5) i += 1 async def run_very_long_task(): await asyncio.sleep(3) return 42 async def supervisor(): loading_task = asyncio.ensure_future(loading()) content = await run_very_long_task() loading_task.cancel() print('The result is {}'.format(content)) loop = asyncio.get_event_loop() loop.run_until_complete(supervisor()) loop.close()
  • 25. pen4education import asyncio import time def slow_function(): time.sleep(3) return 42 async def test1(): slow_function() print('Finish test1') async def test2(): for i in range(0, 10): print(i) await asyncio.sleep(0.5) print('Finish test2') loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([ test1(), test2() ])) Bloqueio do Loop Finish test1 0 1 2 3 4 5 6 7 8 9 Finish test2
  • 26. pen4education import asyncio import time def slow_function(): time.sleep(3) return 42 async def test1(): await loop.run_in_executor(None, slow_function) print('Finish test1') async def test2(): for i in range(0, 10): print(i) await asyncio.sleep(0.5) print('Finish test2') loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([ test1(), test2() ])) Bloqueio do Loop 0 1 2 3 4 5 Finish test1 6 7 8 9 Finish test2
  • 27. pen4education O que ver a seguir? ● ThreadPoolExecutor ● aioHTTP