Skip to Content
Python Microservices Development
book

Python Microservices Development

by Tarek Ziadé
July 2017
Beginner to intermediate
340 pages
7h 43m
English
Packt Publishing
Content preview from Python Microservices Development

Iterators and generators

To understand how asynchronous programming works in Python, it is important to first understand how iterators and generators work because they are the basis of asynchronous features in Python.

An iterator in Python is a class that implements the Iterator protocol. The class must implement the following two methods:

  • __iter__(): ; ;Returns the actual iterator. It often returns self
  • next(): ;Returns the next value until StopIteration() is raised

In the following example, we'll implement the Fibonacci sequence as an iterator:

 class Fibo: def __init__(self, max=10): self.a, self.b = 0, 1 self.max = max self.count = 0 def __iter__(self): return self def next(self): try: return self.a finally: if self.count == self.max: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python Microservices Development - Second Edition

Python Microservices Development - Second Edition

Simon Fraser, Tarek Ziadé
Python Web Development with Sanic

Python Web Development with Sanic

Stephen Sadowski, Adam Hopkins

Publisher Resources

ISBN: 9781785881114Supplemental Content