SlideShare a Scribd company logo
1 of 19
Iterator Pattern:
Generator Expressions
Damian Gordon
Generator Expressions
Iterator Pattern
• Let’s imagine we are processing a large log file:
Iterator Pattern
• Let’s imagine we are processing a large log file:
:
:
Jan 26, 2010 11:25:25 DEBUG This is a debugging message.
Jan 26, 2010 11:25:36 INFO This is an information method.
Jan 26, 2010 11:25:46 WARNING This is a warning. It could be serious.
Jan 26, 2010 11:25:52 WARNING Another warning sent.
Jan 26, 2010 11:25:59 INFO Here's some information.
Jan 26, 2010 11:26:13 DEBUG Debug messages.
Jan 26, 2010 11:26:32 INFO Information is usually harmless, but helpful.
Jan 26, 2010 11:26:40 WARNING Warnings should be heeded.
Jan 26, 2010 11:26:54 WARNING Watch for warnings.
:
:
Iterator Pattern
• If the log file is very big (a few terabytes) and we were looking
only for “WARNING” messages, we shouldn’t use a List
Comprehension in this case because it would temporarily
create a list containing every line and then search for the
appropriate messages.
• Instead we can use Generator Expressions (or Generators).
Iterator Pattern
• To create a Generator Expressions we simply wrap the
comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’.
Iterator Pattern
• To create a Generator Expressions we simply wrap the
comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’.
import sys
InName = "InputFile.txt"
OutName = "OutputFile.txt"
with open(InName) as infile:
with open(OutName, "w") as outfile:
warnings = (line for line in infile if 'WARNING' in line)
for line in warnings:
# DO
outfile.write(line)
# ENDFOR;
# END.
Iterator Pattern
• To create a Generator Expressions we simply wrap the
comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’.
import sys
InName = "InputFile.txt"
OutName = "OutputFile.txt"
with open(InName) as infile:
with open(OutName, "w") as outfile:
warnings = (line for line in infile if 'WARNING' in line)
for line in warnings:
# DO
outfile.write(line)
# ENDFOR;
# END.
Write each line that
matches the criteria
into “warnings”
Call each line in the file
line, one after the next,
after the next
Select only lines that have
the word “WARNING”
Iterator Pattern
• To create a Generator Expressions we simply wrap the
comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’.
import sys
InName = "InputFile.txt"
OutName = "OutputFile.txt"
with open(InName) as infile:
with open(OutName, "w") as outfile:
warnings = (line for line in infile if 'WARNING' in line)
for line in warnings:
# DO
outfile.write(line)
# ENDFOR;
# END.
Write each line that
matches the criteria
into “warnings”
Call each line in the file
line, one after the next,
after the next
Select only lines that have
the word “WARNING”
Create this variable as a
generator expression
Iterator Pattern
• Our output file will look like this:
Jan 26, 2010 11:25:46 WARNING This is a warning. It could be serious.
Jan 26, 2010 11:25:52 WARNING Another warning sent.
Jan 26, 2010 11:26:40 WARNING Warnings should be heeded.
Jan 26, 2010 11:26:54 WARNING Watch for warnings.
Iterator Pattern
• All of the lines in the output file say ‘WARNING’:
Iterator Pattern
• All of the lines in the output file say ‘WARNING’:
Jan 26, 2010 11:25:46 WARNING This is a warning. It could be serious.
Jan 26, 2010 11:25:52 WARNING Another warning sent.
Jan 26, 2010 11:26:40 WARNING Warnings should be heeded.
Jan 26, 2010 11:26:54 WARNING Watch for warnings.
Iterator Pattern
• So we could write a new program to delete the word
“WARNING” out of each line:
Iterator Pattern
• So we could write a new program to delete the word
“WARNING” out of each line:
import sys
inname = "OutputFile.txt"
outname = "OutputFile2.txt"
with open(inname) as infile:
with open(outname, "w") as outfile:
warnings = (line.replace(' WARNING', '')
for line in infile if 'WARNING' in line)
for line in warnings:
outfile.write(line)
# ENDFOR;
# END.
Iterator Pattern
• And we get:
Jan 26, 2010 11:25:46 This is a warning. It could be serious.
Jan 26, 2010 11:25:52 Another warning sent.
Jan 26, 2010 11:26:40 Warnings should be heeded.
Jan 26, 2010 11:26:54 Watch for warnings.
Iterator Pattern
• To do the same thing in a more object-oriented manner:
Iterator Pattern
import sys
inname = "OutputFile.txt"
outname = "OutputFile3.txt"
def warnings_filter(insequence):
for line in insequence:
if 'WARNING' in line:
yield line.replace(' WARNING', '')
with open(inname) as infile:
with open(outname, "w") as outfile:
filter = warnings_filter(infile)
for line in filter:
outfile.write(line)
• To do the same thing in a more object-oriented manner:
Iterator Pattern
import sys
inname = "OutputFile.txt"
outname = "OutputFile3.txt"
def warnings_filter(insequence):
for line in insequence:
if 'WARNING' in line:
yield line.replace(' WARNING', '')
with open(inname) as infile:
with open(outname, "w") as outfile:
filter = warnings_filter(infile)
for line in filter:
outfile.write(line)
• To do the same thing in a more object-oriented manner:
The yield command works exactly
like the normal return command
(when you return a value from a
method), but it temporarily returns
control to the calling method, and
remembers where it was in a
sequence in each new call.
etc.

More Related Content

Viewers also liked

The beauty of food
The beauty of foodThe beauty of food
The beauty of foodzenmariku
 
Acuerdo 444 marco_curricular_comun_snb
Acuerdo 444 marco_curricular_comun_snbAcuerdo 444 marco_curricular_comun_snb
Acuerdo 444 marco_curricular_comun_snbDaniel Desmoctt
 
Mini market bab iii
Mini market   bab iiiMini market   bab iii
Mini market bab iiiimecommunity
 
Put your polling station on the map
Put your polling station on the mapPut your polling station on the map
Put your polling station on the mapFiifi Baidoo
 
Hackers and Hollywood: Extended scene 3
Hackers and Hollywood: Extended scene 3Hackers and Hollywood: Extended scene 3
Hackers and Hollywood: Extended scene 3Damian T. Gordon
 
Databases: Backup and Recovery
Databases: Backup and RecoveryDatabases: Backup and Recovery
Databases: Backup and RecoveryDamian T. Gordon
 
Socialondemand newsondemand purechannelapps_2014
Socialondemand newsondemand purechannelapps_2014Socialondemand newsondemand purechannelapps_2014
Socialondemand newsondemand purechannelapps_2014Chris May
 

Viewers also liked (14)

TRIZ - v2.0
TRIZ - v2.0TRIZ - v2.0
TRIZ - v2.0
 
I like it
I like itI like it
I like it
 
The beauty of food
The beauty of foodThe beauty of food
The beauty of food
 
Acuerdo 444 marco_curricular_comun_snb
Acuerdo 444 marco_curricular_comun_snbAcuerdo 444 marco_curricular_comun_snb
Acuerdo 444 marco_curricular_comun_snb
 
Team work opp
Team work oppTeam work opp
Team work opp
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
Mini market bab iii
Mini market   bab iiiMini market   bab iii
Mini market bab iii
 
Put your polling station on the map
Put your polling station on the mapPut your polling station on the map
Put your polling station on the map
 
Connecting with students
Connecting with studentsConnecting with students
Connecting with students
 
Goldfish Acte[1]
Goldfish Acte[1]Goldfish Acte[1]
Goldfish Acte[1]
 
Hackers and Hollywood: Extended scene 3
Hackers and Hollywood: Extended scene 3Hackers and Hollywood: Extended scene 3
Hackers and Hollywood: Extended scene 3
 
Databases: Backup and Recovery
Databases: Backup and RecoveryDatabases: Backup and Recovery
Databases: Backup and Recovery
 
Socialondemand newsondemand purechannelapps_2014
Socialondemand newsondemand purechannelapps_2014Socialondemand newsondemand purechannelapps_2014
Socialondemand newsondemand purechannelapps_2014
 
Six Word Stories
Six Word StoriesSix Word Stories
Six Word Stories
 

Similar to Python: The Iterator Pattern (Generators)

import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docxwilcockiris
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File ConceptsANUSUYA S
 
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdfCode In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdfaishwaryaequipment
 
The program reads data from two files, itemsList-0x.txt and .docx
The program reads data from two files, itemsList-0x.txt and .docxThe program reads data from two files, itemsList-0x.txt and .docx
The program reads data from two files, itemsList-0x.txt and .docxoscars29
 
Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3FabMinds
 
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...Joachim Jacob
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonmckennadglyn
 
Tricks to hack notepad
Tricks to hack notepadTricks to hack notepad
Tricks to hack notepadVikranChauhan
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
Lecture1_cis4930.pdf
Lecture1_cis4930.pdfLecture1_cis4930.pdf
Lecture1_cis4930.pdfzertash1
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
 
C++ course start
C++ course startC++ course start
C++ course startNet3lem
 
How To Add System Call In Ubuntu OS
How To Add System Call In Ubuntu OSHow To Add System Call In Ubuntu OS
How To Add System Call In Ubuntu OSPratik Tambekar
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
15 Text files
15 Text files15 Text files
15 Text filesmaznabili
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java ProgrammingAhmed Ayman
 

Similar to Python: The Iterator Pattern (Generators) (20)

import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdfCode In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
 
The program reads data from two files, itemsList-0x.txt and .docx
The program reads data from two files, itemsList-0x.txt and .docxThe program reads data from two files, itemsList-0x.txt and .docx
The program reads data from two files, itemsList-0x.txt and .docx
 
Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3
 
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Tricks to hack notepad
Tricks to hack notepadTricks to hack notepad
Tricks to hack notepad
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Baabtra.com little coder chapter - 2
Baabtra.com little coder   chapter - 2Baabtra.com little coder   chapter - 2
Baabtra.com little coder chapter - 2
 
15. text files
15. text files15. text files
15. text files
 
Lecture1_cis4930.pdf
Lecture1_cis4930.pdfLecture1_cis4930.pdf
Lecture1_cis4930.pdf
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docx
 
C++ course start
C++ course startC++ course start
C++ course start
 
Module-1.pptx
Module-1.pptxModule-1.pptx
Module-1.pptx
 
How To Add System Call In Ubuntu OS
How To Add System Call In Ubuntu OSHow To Add System Call In Ubuntu OS
How To Add System Call In Ubuntu OS
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python basics
Python basicsPython basics
Python basics
 
15 Text files
15 Text files15 Text files
15 Text files
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java Programming
 

More from Damian T. Gordon

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Damian T. Gordon
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesDamian T. Gordon
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingDamian T. Gordon
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSDamian T. Gordon
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOTDamian T. Gordon
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricDamian T. Gordon
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDamian T. Gordon
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSUREDamian T. Gordon
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDamian T. Gordon
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDamian T. Gordon
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDamian T. Gordon
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsDamian T. Gordon
 

More from Damian T. Gordon (20)

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Cloud Identity Management
Cloud Identity ManagementCloud Identity Management
Cloud Identity Management
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Introduction to ChatGPT
Introduction to ChatGPTIntroduction to ChatGPT
Introduction to ChatGPT
 
How to Argue Logically
How to Argue LogicallyHow to Argue Logically
How to Argue Logically
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONS
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOT
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson Rubric
 
Evaluating Teaching: LORI
Evaluating Teaching: LORIEvaluating Teaching: LORI
Evaluating Teaching: LORI
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause Procedure
 
Designing Teaching: ADDIE
Designing Teaching: ADDIEDesigning Teaching: ADDIE
Designing Teaching: ADDIE
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSURE
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning Types
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of Instruction
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration Theory
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some Considerations
 

Recently uploaded

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 

Recently uploaded (20)

9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 

Python: The Iterator Pattern (Generators)

  • 3. Iterator Pattern • Let’s imagine we are processing a large log file:
  • 4. Iterator Pattern • Let’s imagine we are processing a large log file: : : Jan 26, 2010 11:25:25 DEBUG This is a debugging message. Jan 26, 2010 11:25:36 INFO This is an information method. Jan 26, 2010 11:25:46 WARNING This is a warning. It could be serious. Jan 26, 2010 11:25:52 WARNING Another warning sent. Jan 26, 2010 11:25:59 INFO Here's some information. Jan 26, 2010 11:26:13 DEBUG Debug messages. Jan 26, 2010 11:26:32 INFO Information is usually harmless, but helpful. Jan 26, 2010 11:26:40 WARNING Warnings should be heeded. Jan 26, 2010 11:26:54 WARNING Watch for warnings. : :
  • 5. Iterator Pattern • If the log file is very big (a few terabytes) and we were looking only for “WARNING” messages, we shouldn’t use a List Comprehension in this case because it would temporarily create a list containing every line and then search for the appropriate messages. • Instead we can use Generator Expressions (or Generators).
  • 6. Iterator Pattern • To create a Generator Expressions we simply wrap the comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’.
  • 7. Iterator Pattern • To create a Generator Expressions we simply wrap the comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’. import sys InName = "InputFile.txt" OutName = "OutputFile.txt" with open(InName) as infile: with open(OutName, "w") as outfile: warnings = (line for line in infile if 'WARNING' in line) for line in warnings: # DO outfile.write(line) # ENDFOR; # END.
  • 8. Iterator Pattern • To create a Generator Expressions we simply wrap the comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’. import sys InName = "InputFile.txt" OutName = "OutputFile.txt" with open(InName) as infile: with open(OutName, "w") as outfile: warnings = (line for line in infile if 'WARNING' in line) for line in warnings: # DO outfile.write(line) # ENDFOR; # END. Write each line that matches the criteria into “warnings” Call each line in the file line, one after the next, after the next Select only lines that have the word “WARNING”
  • 9. Iterator Pattern • To create a Generator Expressions we simply wrap the comprehension in parenthesis ‘()’ instead of ‘[]’ or ‘{}’. import sys InName = "InputFile.txt" OutName = "OutputFile.txt" with open(InName) as infile: with open(OutName, "w") as outfile: warnings = (line for line in infile if 'WARNING' in line) for line in warnings: # DO outfile.write(line) # ENDFOR; # END. Write each line that matches the criteria into “warnings” Call each line in the file line, one after the next, after the next Select only lines that have the word “WARNING” Create this variable as a generator expression
  • 10. Iterator Pattern • Our output file will look like this: Jan 26, 2010 11:25:46 WARNING This is a warning. It could be serious. Jan 26, 2010 11:25:52 WARNING Another warning sent. Jan 26, 2010 11:26:40 WARNING Warnings should be heeded. Jan 26, 2010 11:26:54 WARNING Watch for warnings.
  • 11. Iterator Pattern • All of the lines in the output file say ‘WARNING’:
  • 12. Iterator Pattern • All of the lines in the output file say ‘WARNING’: Jan 26, 2010 11:25:46 WARNING This is a warning. It could be serious. Jan 26, 2010 11:25:52 WARNING Another warning sent. Jan 26, 2010 11:26:40 WARNING Warnings should be heeded. Jan 26, 2010 11:26:54 WARNING Watch for warnings.
  • 13. Iterator Pattern • So we could write a new program to delete the word “WARNING” out of each line:
  • 14. Iterator Pattern • So we could write a new program to delete the word “WARNING” out of each line: import sys inname = "OutputFile.txt" outname = "OutputFile2.txt" with open(inname) as infile: with open(outname, "w") as outfile: warnings = (line.replace(' WARNING', '') for line in infile if 'WARNING' in line) for line in warnings: outfile.write(line) # ENDFOR; # END.
  • 15. Iterator Pattern • And we get: Jan 26, 2010 11:25:46 This is a warning. It could be serious. Jan 26, 2010 11:25:52 Another warning sent. Jan 26, 2010 11:26:40 Warnings should be heeded. Jan 26, 2010 11:26:54 Watch for warnings.
  • 16. Iterator Pattern • To do the same thing in a more object-oriented manner:
  • 17. Iterator Pattern import sys inname = "OutputFile.txt" outname = "OutputFile3.txt" def warnings_filter(insequence): for line in insequence: if 'WARNING' in line: yield line.replace(' WARNING', '') with open(inname) as infile: with open(outname, "w") as outfile: filter = warnings_filter(infile) for line in filter: outfile.write(line) • To do the same thing in a more object-oriented manner:
  • 18. Iterator Pattern import sys inname = "OutputFile.txt" outname = "OutputFile3.txt" def warnings_filter(insequence): for line in insequence: if 'WARNING' in line: yield line.replace(' WARNING', '') with open(inname) as infile: with open(outname, "w") as outfile: filter = warnings_filter(infile) for line in filter: outfile.write(line) • To do the same thing in a more object-oriented manner: The yield command works exactly like the normal return command (when you return a value from a method), but it temporarily returns control to the calling method, and remembers where it was in a sequence in each new call.
  • 19. etc.