Book Image

Mastering Python

By : Rick van Hattem
Book Image

Mastering Python

By: Rick van Hattem

Overview of this book

Python is a dynamic programming language. It is known for its high readability and hence it is often the first language learned by new programmers. Python being multi-paradigm, it can be used to achieve the same thing in different ways and it is compatible across different platforms. Even if you find writing Python code easy, writing code that is efficient, easy to maintain, and reuse is not so straightforward. This book is an authoritative guide that will help you learn new advanced methods in a clear and contextualised way. It starts off by creating a project-specific environment using venv, introducing you to different Pythonic syntax and common pitfalls before moving on to cover the functional features in Python. It covers how to create different decorators, generators, and metaclasses. It also introduces you to functools.wraps and coroutines and how they work. Later on you will learn to use asyncio module for asynchronous clients and servers. You will also get familiar with different testing systems such as py.test, doctest, and unittest, and debugging tools such as Python debugger and faulthandler. You will learn to optimize application performance so that it works efficiently across multiple machines and Python versions. Finally, it will teach you how to access C functions with a simple Python call. By the end of the book, you will be able to write more advanced scripts and take on bigger challenges.
Table of Contents (22 chapters)
Mastering Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
6
Generators and Coroutines – Infinity, One Step at a Time
Index

What are generators?


A generator, in its simplest form, is a function that returns elements one at a time instead of returning a collection of items. The most important advantage of this is that it requires very little memory and that it doesn't need to have a predefined size. Creating an endless generator (such as the itertools.count iterator discussed in Chapter 4, Functional Programming – Readability Versus Brevity) is actually quite easy, but it does come with a cost, of course. Not having the size of an object available makes certain patterns difficult to achieve.

The basic trick in writing generators (as functions) is using the yield statement. Let's use the itertools.count generator as an example and extend it with a stop variable:

>>> def count(start=0, step=1, stop=10):
...     n = start
...     while n <= stop:
...         yield n
...         n += step

>>> for x in count(10, 2.5, 20):
...     print(x)
10
12.5
15.0
17.5
20.0

Due to the potentially infinite nature...