SlideShare a Scribd company logo
Dealing with Python Reactively
PyCon Korea 2017
Kenneth
SPEAKER
Editor
Dev team leader
Kenneth
INTRODUCTION
Ractive Progamming
RxPy
Coroutine / Generator
CH1.
CH2.
CH3.
CH1.
Reactive Programming
What is reactive programming?
CH 1. Reactive Programming
The new paradigm that focused
on the asynchronous data flow
Difficult
Key keyword #1
CH 1. Reactive Programming
Asynchronous
It can be received the data that is not guaranteed
In the asynchronous environment sequentially,
And also it can be processed the data flexible.
Key keyword #2
CH 1. Reactive Programming
Reactive
It is not executed if there is no operation (input) from the outside.
Key keyword #3
CH 1. Reactive Programming
Lightweight
Data flow can be subdivided for each purpose,
And also it can be merged again.
This makes it possible to reduce the weight.
The data flows.
CH 1. Reactive Programming
However it does not flow at the same time.
So we can not guarantee
that the data always comes.
CH 1. Reactive Programming
It can not be easy to process the data
that comes every another times.
CH 1. Reactive Programming
.next() .subscribe()
Controlling multiple data flows.
Reactive programming makes it possible.
CH 1. Reactive Programming
The data that comes from each different times concurrently,
To be sequentially
It only see the data flows.
That’s why it’s intuitive.
CH 1. Reactive Programming
Map
Filter
Merge Reduce
On Complete
On Error
Retry
Skip Buffer
CH2.
RxPy
ReactiveX (RX)
CH 2. RxPy
Microsoft announced `Volta` project in 2007
It is officially known as `Reactive Extensions` in 2009
It was gradually released as open source since 2012
def observer_generator(observer):
# It passes the string “hello” through the observer.
observer.on_next("hello")
# Likewise, it passes the string "world!" through the observer.
observer.on_next("world!")
def main():
# Create an observer, passes it to a predefined function, and receives an object that can receive it.
observable = Observable.create(observer_generator)
# Receive the observer, At this time the observer read the variable that passed at on_next.
# Oh! After the below subscribe is started, the above observer_generator will be executed.
observable.subscribe(on_next=lambda value: print(value))
hello_world.py
observable.create (Create an observer)
observer_generator
observer
def observer_generator(observer):
# It passes the string “hello” through the observer.
observer.on_next("hello")
# Likewise, it passes the string "world!" through the observer.
observer.on_next("world!")
def main():
# Create an observer, passes it to a predefined function, and receives an object that can receive it.
observable = Observable.create(observer_generator)
# Receive the observer, At this time the observer read the variable that passed at on_next.
# Oh! After the below subscribe is started, the above observer_generator will be executed.
observable.subscribe(on_next=lambda value: print(value))
hello_world.py
observable
1. next(‘hello’)
2. next(‘world!’)
observer
1. print(‘hello’)
2. print(‘world!’)
It passes the data through on_next
Print the message that received from on_next
from rx import Observable, Observer
class PrintObserver(Observer):
def on_next(self, value):
print('on_next value:%s’ % (value))
def on_completed(self):
print('on_completed !')
def on_error(self, value):
print('on_error value:%s’ % (value))
def observer_generator(observer):
observer.on_next(“break")
observer.on_next(“the ice!")
while True:
message = input()
if message:
observer.on_next(message)
else:
observer.on_completed()
break
def main():
observable = Observable.create(observer_generator)
observable.subscribe(PrintObserver())
ice_breaking.py
Observable
(Data forwarder)
Observable
(Data receiver)
subscribe()
next(‘break’)
next(‘the ice!’)
next(‘message’)
print()
print()
print()
on_next
on_next
on_next
completed()
on_completed print()
1. You can expand incoming messages by using
Predefined object in Subscribe method.
CH3.
Coroutine / Generator
Coroutine?
CH 3. Coroutine / Generator
Unlike functions,
Routines whose parents are
“equivalent” to the called function.
Python only: Coroutine can process
only the received data.
Coroutine vs General routine
CH 3. Coroutine / Generator
General
Routine
Function
call
Return
Parameters
Result
Coroutine
Function
call
Parameters
Yield
Yield
Yield
Main code Main code
Calculating
Calculating
Calculating
Send
Send
Send
Use Case
CH 3. Coroutine / Generator
Init Data
Caller Coroutine
2. Wait for the caller's input via yield
(Will be returned to caller code lines)
1. Inserting initial data to apply to coroutines
3. If you have input to the caller,
return to the coroutine code and execute the logic.
If yield appearsin the logic,
it returns to the parent code again.
(repeat)
next()
Yield
Yield
4. Finally, the caller ends the coroutine.
Close
Generator?
CH 3. Coroutine / Generator
If Coroutine is a gourmand,
The Generator is the giving tree.
A generator is a `generator`
that generates data through yield.
Do you know range function?
CH 3. Coroutine / Generator
def main():
# Use the range function to insert each value from 0 to 2
# into value and repeat it three times.
for value in range(3):
print(u’current value %d' % (value))
OUTPUT:
current_value 0
current_value 1
current_value 2
Making range function by using Generator.
CH 3. Coroutine / Generator
# It is the range function created by using the Generator.
def custom_range(number):
index = 0
while(index < number):
# At this point, we go back to the parent that called this function,
# Pass the value, and proceed to the parent's logic until we call this function again.
# This is the heart of the generator. Remember this!
yield index
index += 1
coroutine_generator.py
def main():
# Let's try to use the existing range function.
for value in range(3):
print(u'original range %d' % (value))
# Insert a line escaping for the division.
print(u'n')
# Let's try the function we just created.
for value in custom_range(3):
print(u'custom range %d' % (value))
OUTPUT
original range 0
original range 1
original range 2
custom range 0
custom range 1
custom range 2
Use Case
CH 3. Coroutine / Generator
Large Data
Memory
Process
yield
1. In a real-time cursor,
yield returns
every 500 datasets.
2. Actually there are only 500 data in memory,
so there is out of memory problem.
3. When 500 data are processed
and the process is finished,
500 data will be emptied from the memory.
Likewise, there is no out of memory problem.
4. At the end of the process,
it again gets 500 data from Large Data.
Conclusion about Generator
CH 3. Coroutine / Generator
Data that comes in real time
can be used to stabilize
the memory by using the generator!
(Performance difference is insignificant)
What is the difference
Between Coroutine and Generator?
CH 3. Coroutine / Generator
Corutine
Function
call
Parameters
Yield
Yield
Yield
Main code
Calculating
Calculating
Calculating
Send
Send
Generator
Function
call
Parameters
Yield
Yield
Yield
Main code
Calculating
Calculating
Calculating
Return
Return
Return
Send
Question
Thank you
Kennethan@nhpcw.com
http://github.com/KennethanCeyer/pycon-kr-2017
Email
GitHub

More Related Content

PPTX
Promises, promises, and then observables
PPTX
Lecture 4
PDF
Websocket on Rails
PDF
PDF
Practical TypeScript
PPTX
WordPress Hooks Action & Filters
DOCX
Ete programs
PDF
Json.parse() in JavaScript
Promises, promises, and then observables
Lecture 4
Websocket on Rails
Practical TypeScript
WordPress Hooks Action & Filters
Ete programs
Json.parse() in JavaScript

What's hot (20)

PDF
JavaScript promise
DOC
Lesson 5
PPTX
Lecture 3
PPTX
Java Script Promise
PDF
Callbacks and control flow in Node js
PPTX
Demanding scripting
DOCX
Difference between switch and ladder if
PPTX
Evaluation of prefix expression with example
PPTX
Java script function
PPT
Lect 15-16 Zaheer Abbas
PDF
Java input Scanner
PPT
Evolution of asynchrony in (ASP).NET
PDF
Java Repetiotion Statements
PPT
Timedobserver
PDF
Async History - javascript
PPT
Function
PPT
Simulation structure - Part 2
PPTX
Computer
PPT
Fixing an annoying GridView problem
JavaScript promise
Lesson 5
Lecture 3
Java Script Promise
Callbacks and control flow in Node js
Demanding scripting
Difference between switch and ladder if
Evaluation of prefix expression with example
Java script function
Lect 15-16 Zaheer Abbas
Java input Scanner
Evolution of asynchrony in (ASP).NET
Java Repetiotion Statements
Timedobserver
Async History - javascript
Function
Simulation structure - Part 2
Computer
Fixing an annoying GridView problem
Ad

Viewers also liked (7)

PPTX
엔지니어 관점에서 바라본 데이터시각화
PPTX
GDG DevFest 2017 Seoul 프론트엔드 모던 프레임워크 낱낱히 파헤치기
PDF
파이썬 리액티브하게 짜기 - PyCon Korea 2017
PDF
역시 Redux
PDF
다함께, FluxUtils 한바퀴!
PDF
Facebook은 React를 왜 만들었을까?
PDF
AngularJS 2, version 1 and ReactJS
엔지니어 관점에서 바라본 데이터시각화
GDG DevFest 2017 Seoul 프론트엔드 모던 프레임워크 낱낱히 파헤치기
파이썬 리액티브하게 짜기 - PyCon Korea 2017
역시 Redux
다함께, FluxUtils 한바퀴!
Facebook은 React를 왜 만들었을까?
AngularJS 2, version 1 and ReactJS
Ad

Similar to Dealing with Python Reactively - PyCon Korea 2017 (20)

PPTX
Introducing to Asynchronous Programming
PDF
Codemania101: The Present, Past and Future of Asynchronous Programming in Python
PDF
software construction and development.pdf
PDF
python interview prep question , 52 questions
PPT
python-message-0.1.0
PPTX
Mastering Reactive Programming in Python with RxPy
PPTX
14-Python-Concepts for data science.pptx
PDF
Python coroutine
PPT
PE1 Module 3.ppt
PPTX
IoT-Week1-Day1-Lab.pptx
PPT
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
PDF
Python indroduction
 
PDF
Python for web security - beginner
PPTX
Python Interview Questions | Python Interview Questions And Answers | Python ...
DOCX
These questions will be a bit advanced level 2
PPTX
The Awesome Python Class Part-3
PDF
Python meetup: coroutines, event loops, and non-blocking I/O
PDF
Data Science with Python 1st Edition Coll. download pdf
Introducing to Asynchronous Programming
Codemania101: The Present, Past and Future of Asynchronous Programming in Python
software construction and development.pdf
python interview prep question , 52 questions
python-message-0.1.0
Mastering Reactive Programming in Python with RxPy
14-Python-Concepts for data science.pptx
Python coroutine
PE1 Module 3.ppt
IoT-Week1-Day1-Lab.pptx
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
Python indroduction
 
Python for web security - beginner
Python Interview Questions | Python Interview Questions And Answers | Python ...
These questions will be a bit advanced level 2
The Awesome Python Class Part-3
Python meetup: coroutines, event loops, and non-blocking I/O
Data Science with Python 1st Edition Coll. download pdf

More from Kenneth Ceyer (11)

PDF
이미지 프로세싱 in Python Open Source - PYCON KOREA 2020
PDF
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
PDF
LP(linear programming) Algorithm
PDF
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
PPTX
하둡 에코시스템 위에서 환상적인 테이크오프 - DSTS 2019
PPTX
AllReduce for distributed learning I/O Extended Seoul
PDF
gRPC와 goroutine 톺아보기 - GDG Golang Korea 2019
PDF
How to use vim
PDF
Test and refactoring
PPTX
Deep dive into Modern frameworks - HTML5 Forum 2018
PDF
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
이미지 프로세싱 in Python Open Source - PYCON KOREA 2020
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
LP(linear programming) Algorithm
AI 연구자를 위한 클린코드 - GDG DevFest Seoul 2019
하둡 에코시스템 위에서 환상적인 테이크오프 - DSTS 2019
AllReduce for distributed learning I/O Extended Seoul
gRPC와 goroutine 톺아보기 - GDG Golang Korea 2019
How to use vim
Test and refactoring
Deep dive into Modern frameworks - HTML5 Forum 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Cloud computing and distributed systems.
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
cuic standard and advanced reporting.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Machine learning based COVID-19 study performance prediction
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
NewMind AI Monthly Chronicles - July 2025
Cloud computing and distributed systems.
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
“AI and Expert System Decision Support & Business Intelligence Systems”
Review of recent advances in non-invasive hemoglobin estimation
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
cuic standard and advanced reporting.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Per capita expenditure prediction using model stacking based on satellite ima...
Machine learning based COVID-19 study performance prediction
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

Dealing with Python Reactively - PyCon Korea 2017

  • 1. Dealing with Python Reactively PyCon Korea 2017 Kenneth
  • 5. What is reactive programming? CH 1. Reactive Programming The new paradigm that focused on the asynchronous data flow
  • 7. Key keyword #1 CH 1. Reactive Programming Asynchronous It can be received the data that is not guaranteed In the asynchronous environment sequentially, And also it can be processed the data flexible.
  • 8. Key keyword #2 CH 1. Reactive Programming Reactive It is not executed if there is no operation (input) from the outside.
  • 9. Key keyword #3 CH 1. Reactive Programming Lightweight Data flow can be subdivided for each purpose, And also it can be merged again. This makes it possible to reduce the weight.
  • 10. The data flows. CH 1. Reactive Programming
  • 11. However it does not flow at the same time. So we can not guarantee that the data always comes. CH 1. Reactive Programming
  • 12. It can not be easy to process the data that comes every another times. CH 1. Reactive Programming .next() .subscribe()
  • 13. Controlling multiple data flows. Reactive programming makes it possible. CH 1. Reactive Programming The data that comes from each different times concurrently, To be sequentially
  • 14. It only see the data flows. That’s why it’s intuitive. CH 1. Reactive Programming Map Filter Merge Reduce On Complete On Error Retry Skip Buffer
  • 16. ReactiveX (RX) CH 2. RxPy Microsoft announced `Volta` project in 2007 It is officially known as `Reactive Extensions` in 2009 It was gradually released as open source since 2012
  • 17. def observer_generator(observer): # It passes the string “hello” through the observer. observer.on_next("hello") # Likewise, it passes the string "world!" through the observer. observer.on_next("world!") def main(): # Create an observer, passes it to a predefined function, and receives an object that can receive it. observable = Observable.create(observer_generator) # Receive the observer, At this time the observer read the variable that passed at on_next. # Oh! After the below subscribe is started, the above observer_generator will be executed. observable.subscribe(on_next=lambda value: print(value)) hello_world.py observable.create (Create an observer) observer_generator observer
  • 18. def observer_generator(observer): # It passes the string “hello” through the observer. observer.on_next("hello") # Likewise, it passes the string "world!" through the observer. observer.on_next("world!") def main(): # Create an observer, passes it to a predefined function, and receives an object that can receive it. observable = Observable.create(observer_generator) # Receive the observer, At this time the observer read the variable that passed at on_next. # Oh! After the below subscribe is started, the above observer_generator will be executed. observable.subscribe(on_next=lambda value: print(value)) hello_world.py observable 1. next(‘hello’) 2. next(‘world!’) observer 1. print(‘hello’) 2. print(‘world!’) It passes the data through on_next Print the message that received from on_next
  • 19. from rx import Observable, Observer class PrintObserver(Observer): def on_next(self, value): print('on_next value:%s’ % (value)) def on_completed(self): print('on_completed !') def on_error(self, value): print('on_error value:%s’ % (value)) def observer_generator(observer): observer.on_next(“break") observer.on_next(“the ice!") while True: message = input() if message: observer.on_next(message) else: observer.on_completed() break def main(): observable = Observable.create(observer_generator) observable.subscribe(PrintObserver()) ice_breaking.py Observable (Data forwarder) Observable (Data receiver) subscribe() next(‘break’) next(‘the ice!’) next(‘message’) print() print() print() on_next on_next on_next completed() on_completed print() 1. You can expand incoming messages by using Predefined object in Subscribe method.
  • 21. Coroutine? CH 3. Coroutine / Generator Unlike functions, Routines whose parents are “equivalent” to the called function. Python only: Coroutine can process only the received data.
  • 22. Coroutine vs General routine CH 3. Coroutine / Generator General Routine Function call Return Parameters Result Coroutine Function call Parameters Yield Yield Yield Main code Main code Calculating Calculating Calculating Send Send Send
  • 23. Use Case CH 3. Coroutine / Generator Init Data Caller Coroutine 2. Wait for the caller's input via yield (Will be returned to caller code lines) 1. Inserting initial data to apply to coroutines 3. If you have input to the caller, return to the coroutine code and execute the logic. If yield appearsin the logic, it returns to the parent code again. (repeat) next() Yield Yield 4. Finally, the caller ends the coroutine. Close
  • 24. Generator? CH 3. Coroutine / Generator If Coroutine is a gourmand, The Generator is the giving tree. A generator is a `generator` that generates data through yield.
  • 25. Do you know range function? CH 3. Coroutine / Generator def main(): # Use the range function to insert each value from 0 to 2 # into value and repeat it three times. for value in range(3): print(u’current value %d' % (value)) OUTPUT: current_value 0 current_value 1 current_value 2
  • 26. Making range function by using Generator. CH 3. Coroutine / Generator # It is the range function created by using the Generator. def custom_range(number): index = 0 while(index < number): # At this point, we go back to the parent that called this function, # Pass the value, and proceed to the parent's logic until we call this function again. # This is the heart of the generator. Remember this! yield index index += 1
  • 27. coroutine_generator.py def main(): # Let's try to use the existing range function. for value in range(3): print(u'original range %d' % (value)) # Insert a line escaping for the division. print(u'n') # Let's try the function we just created. for value in custom_range(3): print(u'custom range %d' % (value)) OUTPUT original range 0 original range 1 original range 2 custom range 0 custom range 1 custom range 2
  • 28. Use Case CH 3. Coroutine / Generator Large Data Memory Process yield 1. In a real-time cursor, yield returns every 500 datasets. 2. Actually there are only 500 data in memory, so there is out of memory problem. 3. When 500 data are processed and the process is finished, 500 data will be emptied from the memory. Likewise, there is no out of memory problem. 4. At the end of the process, it again gets 500 data from Large Data.
  • 29. Conclusion about Generator CH 3. Coroutine / Generator Data that comes in real time can be used to stabilize the memory by using the generator! (Performance difference is insignificant)
  • 30. What is the difference Between Coroutine and Generator? CH 3. Coroutine / Generator Corutine Function call Parameters Yield Yield Yield Main code Calculating Calculating Calculating Send Send Generator Function call Parameters Yield Yield Yield Main code Calculating Calculating Calculating Return Return Return Send