SlideShare a Scribd company logo
1 of 34
Python Coroutine
2016. 2. 24
WAPPLES Dev. Group | KyeongSeob SIM
Using the python fluently
I. Coroutine intro
II. Generator
III. Decorator
IV. First-Class Citizen
V. Coroutine in python
VI. QnA
Contents
Coroutine Intro
- Components that generalize subroutines for non-
preemptive multitasking.
- Allowing multiple entry points for suspending and
resuming execution at certain locations.
- Well sutied such as cooperative tasks, execptions,
event loop, iteratios, infinite lists and pipes.
- The term coroutine was coined by Melvin Conway in
1958.
Coroutine ?
4
Subroutines
- Begins at the start.
- Once a subroutine exits, it is finished.
- Instance of a subroutine only returns once.
- Does not hold state between invocations.
- Requires only a single stack that can be preallocated
at the start of program execution.
Comparison with subroutines
5
Coroutines
- Can exit by calling other coroutines, which may later
return to the point where they were invoked in the
original coroutine
- Holds state and varies between invocations.
- Can be multiple instances of a given coroutine at once.
- Able to call on other coroutines as peers.
- Creation can be done cheeply by preallocating stacks
or caching previously allocated stacks.
Comparison with subroutines
6
Comparison with subroutines
7
The queue is then completely filed
or emptied before yielding control
to the other coroutine using the yi
eld command.
The further coroutines calls are st
arting right after the yield, in the o
uter coroutine loop.
Coroutines
- Can yield multiple times.
- Suspending their execution.
- Allowing re-entry at multiple entry points.
- Can control where execution continues after they yield.
Comparison with generators
8
Generators
- Also known as semi-coroutines.
- Can’t control where execution continues after they yield.
Transferring control back to the generator’s caller.
- The yield statement in a generator does not specify a
coroutine to jump to, but rather passes a value back to a
parent routine.
- However, it is still possible to implement coroutines.
Comparison with generators
9
Comparison with generators
10
Does the same operation as the
previous example of coroutine.
However, there are differences i
n the role of yield.
The yield statement in a generat
passes a value back to a ‘dispat
cher’ subroutine.
Generator
- Special routine that can be used to control the
iteration behavior of loop.
- In fact, all generators are iterators.
- A generator is very similar to a function that returns an
array.
- Building an array containing all the values and returning
them all at once.
- However, a generator yields the values one at a time.
- In short, a generator looks like a function but behaves
like an iterator.
Generator ?
12
- Generators are usually invoked inside loops.
- Generators compute their yielded values only on demand.
- They are useful for representing streams.
- Such as sequences that would be expensive or impossible to
compute at once.
- These include infinite sequences and live data streams.
When using the generator
13
In python, a generator can be
thought of an iterator that
contains a frozen stack frame.
Whenever the iterator’s “next()”
method called, python resumes
the frozen frame, which
executes normally until the next
yield statement is reached.
The generator’s frame is then
frozen again, and the yielded
value is returned to the caller.
Generator in python
14
Iterator
- An object that enables a programmer to traverse a
container, particularly lists.
- Performs traversal and also gives access to data
elements in a container, but does not perform iteration.
Iterator ?
16
- One way of implementing iterators is to use a
restricted form of coroutine, known as a generator.
- A generator coroutine can yield values to its caller
multiple times, instead of returning just once.
- There are subtle differences and distinctions in the
use of the terms “generator” and “iterator”, which vary
between authors and languages.
Iterator or generator
17
Iterators in python are a
fundamental part of the
language.
And in many cases go unseen
as they are implicitly used.
Iterator in python
18
Decorator
- Not to be confused with the “Decorator pattern” .
- “Decorator pattern” is a design pattern used in statically
typed object-oriented programming languages to allow
functionality to be added to objects at run time.
- Any callable python object.
- That is used to modify a function, method or class definition.
- Passed the original object being defined and modified object,
which is then bound to the name in the definition.
Decorator ?
20
- Inspired in part by “Java annotations”.
- Have a similar syntax.
- Syntax is pure syntactic sugar.
- Using “@” as the keyword.
Decorator ?
21
They enhance the action of the
function or method they decorate.
Canonical uses of function
decrators are for create class
method or static methods,
adding function attributes,
tracing, setting pre- and
postconditions, and
synchronisation.
Decorator in python
22
- In python prior to version 2.6, decorators apply to
functions and methods.
- But not to classes.
- Class decorators are supported starting with python 2.6.
- PEP 3129
Decorator in python
23
First-Class Citizen
- An entity which supports all the operations generally
available to other entities.
- These operations typically include being passed as an
argument, returned from a function, and assigned to a
variable.
- The concept of first- and second- class objects was
introduced by Christopher Strachey in the 1960s.
- But contrasted real numbers and procedures in ALGOL.
First-Class citizen ?
25
- The simplest scalar data types are nearly always first-
class.
- Such as integer and floating-point numbers.
- In many older languages, arrays and strings are not
first-class
- They cannot be assigned as objects or passed as
parameters to a subroutine.
- C appears to support assignment of array pointers, but in
fact these are simply pointers to the array’s first element,
and again do not carry the array’s size.
Examples
26
Coroutine in python
- Threads give python programmers a way to run
multiple functions seemingly at the same time.
- But there are three big problems with threads.
Thread in python
28
1. They require special tools to coordinate with each
other safely.
- Use “lock’ to prevent data race.
- Use “queue” to coordinate work between threads.
- This makes code that uses threads harder to reason about
than procedural, single-threaded code.
- This complexity makes threaded code more difficult to
extend and maintain over time.
Thread problems in python
29
2. Threads require a lot of memory, about 8MB per
executing thread.
3. Threads are costly to start.
- If you want to constantly be creating new concurrent
functions and finishing them, the overhead of using
threads becomes large and slows everything down.
Thread problems in python
30
- Python can work around all thread issues with
coroutines.
- Coroutines let you have many seemingly simultaneous
functions in your python programs.
- The cost of starting a generator coroutine is a
function call.
- They each use less than 1KB of memory until they’re
exhausted.
Coroutine in python
31
Python 2.5 implements better support for coroutine-like
functionality, based on extended generators (PEP 342)
Python 3.3 improves this ability, by supporting delegating
to a subgenerator (PEP 380)
Python 3.4 introduces a comprehensive asynchronous
I/O framework as standardized in PEP 3156, which
includes coroutines that leverage subgenerator
delegation
Python 3.5 introduces explicit support for coroutines with
async/await syntax (PEP 0492)
Coroutine in python
32
QnA
t h a n k y o u
Copyright 2016 Penta Security Systems Inc. All rights reserved.
KOREA
U.S.A.
JAPAN
Yeouido, Seoul www.pentasecurity.com (HQ)
Houston, Texas www.pentasecurity.com/en
Shinjuku-Ku, Tokyo
www.pentasecurity.co.jp

More Related Content

What's hot

Programming using Open Mp
Programming using Open MpProgramming using Open Mp
Programming using Open MpAnshul Sharma
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperabilityrik0
 
Presentation on Shared Memory Parallel Programming
Presentation on Shared Memory Parallel ProgrammingPresentation on Shared Memory Parallel Programming
Presentation on Shared Memory Parallel ProgrammingVengada Karthik Rangaraju
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresIntellipaat
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...DrupalMumbai
 
The dark side of Ruby, or Learn functional programming with Ruby
The dark side of Ruby, or Learn functional programming with RubyThe dark side of Ruby, or Learn functional programming with Ruby
The dark side of Ruby, or Learn functional programming with RubyEvgeny Garlukovich
 
Refactoring Edit History of Source Code
Refactoring Edit History of Source CodeRefactoring Edit History of Source Code
Refactoring Edit History of Source CodeShinpei Hayashi
 
OpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersOpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersDhanashree Prasad
 
Python Generators
Python GeneratorsPython Generators
Python GeneratorsAkshar Raaj
 

What's hot (20)

Open mp directives
Open mp directivesOpen mp directives
Open mp directives
 
Programming using Open Mp
Programming using Open MpProgramming using Open Mp
Programming using Open Mp
 
Introduction to MPI
Introduction to MPIIntroduction to MPI
Introduction to MPI
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperability
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 
Presentation on Shared Memory Parallel Programming
Presentation on Shared Memory Parallel ProgrammingPresentation on Shared Memory Parallel Programming
Presentation on Shared Memory Parallel Programming
 
Python Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python ClosuresPython Closures Explained | What are Closures in Python | Python Closures
Python Closures Explained | What are Closures in Python | Python Closures
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
 
The dark side of Ruby, or Learn functional programming with Ruby
The dark side of Ruby, or Learn functional programming with RubyThe dark side of Ruby, or Learn functional programming with Ruby
The dark side of Ruby, or Learn functional programming with Ruby
 
Refactoring Edit History of Source Code
Refactoring Edit History of Source CodeRefactoring Edit History of Source Code
Refactoring Edit History of Source Code
 
OpenMP Tutorial for Beginners
OpenMP Tutorial for BeginnersOpenMP Tutorial for Beginners
OpenMP Tutorial for Beginners
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
OpenMP And C++
OpenMP And C++OpenMP And C++
OpenMP And C++
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Open mp intro_01
Open mp intro_01Open mp intro_01
Open mp intro_01
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
openmp
openmpopenmp
openmp
 
Python master class part 1
Python master class part 1Python master class part 1
Python master class part 1
 

Similar to Python coroutine

python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questionsgokul174578
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiNico Ludwig
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl Lyndon White
 
Towards Chainer v1.5
Towards Chainer v1.5Towards Chainer v1.5
Towards Chainer v1.5Seiya Tokui
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksEueung Mulyana
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Parallel programming Comparisions
Parallel programming ComparisionsParallel programming Comparisions
Parallel programming ComparisionsMuhammad Bilal Khan
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
Digging into asyncio
Digging into asyncioDigging into asyncio
Digging into asyncioMinJeong Kim
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootVMware Tanzu
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNico Ludwig
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Introduction to Chainer: A Flexible Framework for Deep Learning
Introduction to Chainer: A Flexible Framework for Deep LearningIntroduction to Chainer: A Flexible Framework for Deep Learning
Introduction to Chainer: A Flexible Framework for Deep LearningSeiya Tokui
 
HiPEAC 2019 Tutorial - Maestro RTOS
HiPEAC 2019 Tutorial - Maestro RTOSHiPEAC 2019 Tutorial - Maestro RTOS
HiPEAC 2019 Tutorial - Maestro RTOSTulipp. Eu
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNico Ludwig
 

Similar to Python coroutine (20)

python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questions
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl
 
Towards Chainer v1.5
Towards Chainer v1.5Towards Chainer v1.5
Towards Chainer v1.5
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter Notebooks
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Parallel programming Comparisions
Parallel programming ComparisionsParallel programming Comparisions
Parallel programming Comparisions
 
Python master class 2
Python master class 2Python master class 2
Python master class 2
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Digging into asyncio
Digging into asyncioDigging into asyncio
Digging into asyncio
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Introduction to Chainer: A Flexible Framework for Deep Learning
Introduction to Chainer: A Flexible Framework for Deep LearningIntroduction to Chainer: A Flexible Framework for Deep Learning
Introduction to Chainer: A Flexible Framework for Deep Learning
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
 
HiPEAC 2019 Tutorial - Maestro RTOS
HiPEAC 2019 Tutorial - Maestro RTOSHiPEAC 2019 Tutorial - Maestro RTOS
HiPEAC 2019 Tutorial - Maestro RTOS
 
Pthread
PthreadPthread
Pthread
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 

More from 경섭 심

Python Packaging & Debian Packaging
Python Packaging & Debian PackagingPython Packaging & Debian Packaging
Python Packaging & Debian Packaging경섭 심
 
Debian packaging - Advanced
Debian packaging - AdvancedDebian packaging - Advanced
Debian packaging - Advanced경섭 심
 
Debian packaging - basic process
Debian packaging - basic processDebian packaging - basic process
Debian packaging - basic process경섭 심
 
Ubuntu packaging - deploy package
Ubuntu packaging - deploy packageUbuntu packaging - deploy package
Ubuntu packaging - deploy package경섭 심
 
Ubuntu packaging - make package
Ubuntu packaging - make packageUbuntu packaging - make package
Ubuntu packaging - make package경섭 심
 
More Effective Python 3st (Multitask)
More Effective Python 3st (Multitask)More Effective Python 3st (Multitask)
More Effective Python 3st (Multitask)경섭 심
 
Main Variable Program
Main Variable ProgramMain Variable Program
Main Variable Program경섭 심
 
Python comparing
Python comparingPython comparing
Python comparing경섭 심
 
Debian 패키지 관리 프로세스
Debian 패키지 관리 프로세스Debian 패키지 관리 프로세스
Debian 패키지 관리 프로세스경섭 심
 
Effective Python 2st (Decorator & Generator)
Effective Python 2st (Decorator & Generator)Effective Python 2st (Decorator & Generator)
Effective Python 2st (Decorator & Generator)경섭 심
 
Effective Python 1st (Test & Style)
Effective Python 1st (Test & Style)Effective Python 1st (Test & Style)
Effective Python 1st (Test & Style)경섭 심
 

More from 경섭 심 (11)

Python Packaging & Debian Packaging
Python Packaging & Debian PackagingPython Packaging & Debian Packaging
Python Packaging & Debian Packaging
 
Debian packaging - Advanced
Debian packaging - AdvancedDebian packaging - Advanced
Debian packaging - Advanced
 
Debian packaging - basic process
Debian packaging - basic processDebian packaging - basic process
Debian packaging - basic process
 
Ubuntu packaging - deploy package
Ubuntu packaging - deploy packageUbuntu packaging - deploy package
Ubuntu packaging - deploy package
 
Ubuntu packaging - make package
Ubuntu packaging - make packageUbuntu packaging - make package
Ubuntu packaging - make package
 
More Effective Python 3st (Multitask)
More Effective Python 3st (Multitask)More Effective Python 3st (Multitask)
More Effective Python 3st (Multitask)
 
Main Variable Program
Main Variable ProgramMain Variable Program
Main Variable Program
 
Python comparing
Python comparingPython comparing
Python comparing
 
Debian 패키지 관리 프로세스
Debian 패키지 관리 프로세스Debian 패키지 관리 프로세스
Debian 패키지 관리 프로세스
 
Effective Python 2st (Decorator & Generator)
Effective Python 2st (Decorator & Generator)Effective Python 2st (Decorator & Generator)
Effective Python 2st (Decorator & Generator)
 
Effective Python 1st (Test & Style)
Effective Python 1st (Test & Style)Effective Python 1st (Test & Style)
Effective Python 1st (Test & Style)
 

Recently uploaded

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Recently uploaded (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Python coroutine

  • 1. Python Coroutine 2016. 2. 24 WAPPLES Dev. Group | KyeongSeob SIM Using the python fluently
  • 2. I. Coroutine intro II. Generator III. Decorator IV. First-Class Citizen V. Coroutine in python VI. QnA Contents
  • 4. - Components that generalize subroutines for non- preemptive multitasking. - Allowing multiple entry points for suspending and resuming execution at certain locations. - Well sutied such as cooperative tasks, execptions, event loop, iteratios, infinite lists and pipes. - The term coroutine was coined by Melvin Conway in 1958. Coroutine ? 4
  • 5. Subroutines - Begins at the start. - Once a subroutine exits, it is finished. - Instance of a subroutine only returns once. - Does not hold state between invocations. - Requires only a single stack that can be preallocated at the start of program execution. Comparison with subroutines 5
  • 6. Coroutines - Can exit by calling other coroutines, which may later return to the point where they were invoked in the original coroutine - Holds state and varies between invocations. - Can be multiple instances of a given coroutine at once. - Able to call on other coroutines as peers. - Creation can be done cheeply by preallocating stacks or caching previously allocated stacks. Comparison with subroutines 6
  • 7. Comparison with subroutines 7 The queue is then completely filed or emptied before yielding control to the other coroutine using the yi eld command. The further coroutines calls are st arting right after the yield, in the o uter coroutine loop.
  • 8. Coroutines - Can yield multiple times. - Suspending their execution. - Allowing re-entry at multiple entry points. - Can control where execution continues after they yield. Comparison with generators 8
  • 9. Generators - Also known as semi-coroutines. - Can’t control where execution continues after they yield. Transferring control back to the generator’s caller. - The yield statement in a generator does not specify a coroutine to jump to, but rather passes a value back to a parent routine. - However, it is still possible to implement coroutines. Comparison with generators 9
  • 10. Comparison with generators 10 Does the same operation as the previous example of coroutine. However, there are differences i n the role of yield. The yield statement in a generat passes a value back to a ‘dispat cher’ subroutine.
  • 12. - Special routine that can be used to control the iteration behavior of loop. - In fact, all generators are iterators. - A generator is very similar to a function that returns an array. - Building an array containing all the values and returning them all at once. - However, a generator yields the values one at a time. - In short, a generator looks like a function but behaves like an iterator. Generator ? 12
  • 13. - Generators are usually invoked inside loops. - Generators compute their yielded values only on demand. - They are useful for representing streams. - Such as sequences that would be expensive or impossible to compute at once. - These include infinite sequences and live data streams. When using the generator 13
  • 14. In python, a generator can be thought of an iterator that contains a frozen stack frame. Whenever the iterator’s “next()” method called, python resumes the frozen frame, which executes normally until the next yield statement is reached. The generator’s frame is then frozen again, and the yielded value is returned to the caller. Generator in python 14
  • 16. - An object that enables a programmer to traverse a container, particularly lists. - Performs traversal and also gives access to data elements in a container, but does not perform iteration. Iterator ? 16
  • 17. - One way of implementing iterators is to use a restricted form of coroutine, known as a generator. - A generator coroutine can yield values to its caller multiple times, instead of returning just once. - There are subtle differences and distinctions in the use of the terms “generator” and “iterator”, which vary between authors and languages. Iterator or generator 17
  • 18. Iterators in python are a fundamental part of the language. And in many cases go unseen as they are implicitly used. Iterator in python 18
  • 20. - Not to be confused with the “Decorator pattern” . - “Decorator pattern” is a design pattern used in statically typed object-oriented programming languages to allow functionality to be added to objects at run time. - Any callable python object. - That is used to modify a function, method or class definition. - Passed the original object being defined and modified object, which is then bound to the name in the definition. Decorator ? 20
  • 21. - Inspired in part by “Java annotations”. - Have a similar syntax. - Syntax is pure syntactic sugar. - Using “@” as the keyword. Decorator ? 21
  • 22. They enhance the action of the function or method they decorate. Canonical uses of function decrators are for create class method or static methods, adding function attributes, tracing, setting pre- and postconditions, and synchronisation. Decorator in python 22
  • 23. - In python prior to version 2.6, decorators apply to functions and methods. - But not to classes. - Class decorators are supported starting with python 2.6. - PEP 3129 Decorator in python 23
  • 25. - An entity which supports all the operations generally available to other entities. - These operations typically include being passed as an argument, returned from a function, and assigned to a variable. - The concept of first- and second- class objects was introduced by Christopher Strachey in the 1960s. - But contrasted real numbers and procedures in ALGOL. First-Class citizen ? 25
  • 26. - The simplest scalar data types are nearly always first- class. - Such as integer and floating-point numbers. - In many older languages, arrays and strings are not first-class - They cannot be assigned as objects or passed as parameters to a subroutine. - C appears to support assignment of array pointers, but in fact these are simply pointers to the array’s first element, and again do not carry the array’s size. Examples 26
  • 28. - Threads give python programmers a way to run multiple functions seemingly at the same time. - But there are three big problems with threads. Thread in python 28
  • 29. 1. They require special tools to coordinate with each other safely. - Use “lock’ to prevent data race. - Use “queue” to coordinate work between threads. - This makes code that uses threads harder to reason about than procedural, single-threaded code. - This complexity makes threaded code more difficult to extend and maintain over time. Thread problems in python 29
  • 30. 2. Threads require a lot of memory, about 8MB per executing thread. 3. Threads are costly to start. - If you want to constantly be creating new concurrent functions and finishing them, the overhead of using threads becomes large and slows everything down. Thread problems in python 30
  • 31. - Python can work around all thread issues with coroutines. - Coroutines let you have many seemingly simultaneous functions in your python programs. - The cost of starting a generator coroutine is a function call. - They each use less than 1KB of memory until they’re exhausted. Coroutine in python 31
  • 32. Python 2.5 implements better support for coroutine-like functionality, based on extended generators (PEP 342) Python 3.3 improves this ability, by supporting delegating to a subgenerator (PEP 380) Python 3.4 introduces a comprehensive asynchronous I/O framework as standardized in PEP 3156, which includes coroutines that leverage subgenerator delegation Python 3.5 introduces explicit support for coroutines with async/await syntax (PEP 0492) Coroutine in python 32
  • 33. QnA
  • 34. t h a n k y o u Copyright 2016 Penta Security Systems Inc. All rights reserved. KOREA U.S.A. JAPAN Yeouido, Seoul www.pentasecurity.com (HQ) Houston, Texas www.pentasecurity.com/en Shinjuku-Ku, Tokyo www.pentasecurity.co.jp