Iterators and Generators Thomas Wouters XS4ALL

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
And other languages….  Selection Statements  Iterative Statements  Unconditional Branching  Not covered Guarded Commands.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Lilian Blot TPOP Practical Assignment Optional, but you are strongly encourage to do it, especially if you are new to programming Available on Module.
COMPSCI 105 S Principles of Computer Science Linked Lists 2.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Copyright © Texas Education Agency, Computer Programming For Loops.
/t/ / I d/ /d/ Try Again Go on /t/ / I d/ /d/
Python Control of Flow.
Python, Part 2. Python Object Equality x == y x is y In Java: (x.equals(y)) (x == y)
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Chapter 2 Control. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Repetition, quick overview.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Python – May 17 Recap lab Multidimensional list Exceptions Commitment: quiz tomorrow.
New-Style Classes Thomas Wouters XS4ALL #python.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
If statements while loop for loop
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Python iterators and generators. Iterators and generators  Python makes good use of iterators  And has a special kind of generator function that is.
Chapter 14 Advanced Function Topics CSC1310 Fall 2009.
COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.
Sistem Operasi © Sekolah Tinggi Teknik Surabaya 1.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Python Let’s get started!.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Tirgul 10. What We Will See Today:  Linked lists  Graphs  Trees  Iterators and Generators.
Repetition Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
The Python Language Petr Přikryl Part IIb Socrates IP, 15th June 2004 TU of Brno, FIT, Czech Republic.
Computer Science 112 Fundamentals of Programming II Iterators.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Objects, If, Routines. Creating Objects an object is a fundamental software element that has a state and a set of behaviors. Ex: bank account or student.
Python Documentation Fran Fitzpatrick. Overview  Comments  Documentation Strings  Pydoc  Comments  Documentation Strings  Pydoc.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Iterators and Generators
Intro2CS Tirgul 11.
Lecture 6 Repetition Richard Gesick.
COMP280:Introduction to Software Development Week 10, Lecture 28
Python Classes By Craig Pennell.
CHAPTER FOUR Functions.
Exception Handling.
Python’s Errors and Exceptions
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Python iterators and generators
Python LinkedLists.
ERRORS AND EXCEPTIONS Errors:
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Module 2 - Part 1 Variables, Assignment, and Data Types
Functions So far we've been using functions from the builtin module, which is automatically loaded in most cases. Occasionally we've accessed functions.
Python iterators and generators
Python Reserved Words Poster
Presentation transcript:

Iterators and Generators Thomas Wouters XS4ALL

Overview Iteration Iterators Generators Tasklets Questions

Iteration The act of going over a collection Explicit in the form of ‘for’ Implicit in many forms: –list(), tuple(), dict(), … –map(), reduce(), zip(), … –‘in’ in absence of __contains__() –‘extended call’ syntax: func(*…) but not apply() Uses __getitem__ in Python before 2.2

Iterators Added in Python 2.2 Protocol of 2 methods (no special class): –__iter__(): get iterator –next(): get next value raises StopIteration when done Explicit iterator creation with iter() Turn iteration(-state) into objects Interchangeable with iterable for iteration

iter() Creates a new iterator for an object –Calls __iter__() for creation –Falls back to __getitem__() –Called implicitly for iteration Wraps a function in an iterator –iter(f, o) calls f until o is returned: for line in iter(file.readline, ""): handle(line)

Examples >>> l = [1, 2, 3, 4, 5, 6] >>> it = iter(l) >>> for num in it:... if num > 1: break >>> for num in it:... print num; break 3 >>> print list(it) [4, 5, 6]

Writing Iterators class IRange: def __init__(self, end): self.end = end self.cur = 0 def next(self): cur = self.cur if cur >= self.end: raise StopIteration self.cur += 1 return cur def __iter__(self): return self

Generators Optional in Python 2.2 –from __future__ import generators Use new keyword 'yield' –any function with 'yield' is special Turn function-state into objects Use the iterator protocol Not unavoidable –just very very convenient

IRange generator >>> def irange(end):... cur = 0... while cur < end:... yield cur... cur += 1 >>> print irange(10) >>> print list(irange(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Many useful generators in the 'itertools' module (Python 2.3)

Example def map(func, iterable): result = [] for item in iterable: result.append(func(item)) return result def imap(func, iterable): for item in iterable: yield func(item)

'yield' and 'try'/'finally' Python does not allow 'yield' inside a 'try' block with a 'finally' clause: try: yield x finally: print x 'yield' inside 'finally' or in 'try'/'except' is allowed

Generators as Tasklets Write function as generator –at all pause points before the final result, yield a sentinel value (such as None) –avoid blocking functions, or write them as generators and call in a loop Convince callers to use iteration Remember: you may never be called again

TryAgainLater = object() class Bucket: def __init__(self): self.data = [] self.done = False def __iter__(self): return self def next(self): if self.data: return self.data.pop(0) if self.done: raise StopIteration return TryAgainLater def add(self, item): self.data.append(item) def end(self): self.done = True

class Tasklet: def __init__(self, *args, **kwargs): self._work = self._workgen(*args, **kwargs) def run(self): try: return self._work.next() except StopIteration: return None def _workgen(self, bucket): for item in bucket: if item is TryAgainLater: yield TryAgainLater continue for returnval in self._process(item): yield returnval def _process(self, item): while not item.done: yield TryAgainLater yield item.value

class Tasklet: def __init__(self, *args, **kwargs): self.run = self._workgen(*args, **kwargs).next def _workgen(self, bucket, process): for item in bucket: if item is TryAgainLater: yield TryAgainLater continue for endmarker in process(item): if endmarker is TryAgainLater: yield TryAgainLater break else: raise SuitableError, "process never returned anything" for skipitem in bucket: # eat bucket items until endmarker if skipitem is not endmarker: yield TryAgainLater break else: warnings.warn(SuitableWarning, "marker not found") yield DoneProcessing raise InternalError, "Tasklet finished"

class Tasklet: def __init__(self, *args, **kwargs): self.run = self._workgen(*args).next def _workgen(self, bucket, process): for item in bucket: if item is TryAgainLater: yield TryAgainLater continue for endmarker in process(item): if endmarker is TryAgainLater: yield TryAgainLater break else: raise SuitableError

# for item in bucket: #... for skipitem in bucket: # eat bucket items until # endmarker if skipitem is not endmarker: yield TryAgainLater break else: warnings.warn(SuitableWarning, "marker not found") yield DoneProcessing raise TaskletError, \ "Tasklet finished"

Questions ?