Skip to content

Python: трюки с генераторами для системных программистов

Dmitry Ponyatov edited this page Oct 4, 2019 · 20 revisions

Трюки с генераторами для системных программистов

(версия 3)

(с) David Beazley http://www.dabeaz.com/generators/

Первоначально представлен на PyCon 2008
Обновлено: октябрь 2018 г.

Introduction 3.0

This tutorial was originally presented at PyCon'2008 (Chicago). Although the original tutorial was written for Python 2.5, the underlying concepts remain current. This revised version of the tutorial has been updated to Python 3.7.
Enjoy!

-- Dave Beazley (October 2018)

If you like this tutorial, come to Chicago and take an advanced programming class!

https://www.dabeaz.com/courses.html

Support Files

An Introduction

  • Generators are cool!
  • But what are they?
  • And what are they good for?
  • That's what this tutorial is about

Our Goal

  • Explore practical uses of generators
  • Focus is "systems programming"
  • Which loosely includes files, file systems, parsing, networking, threads, etc.
  • My goal: To provide some more compelling examples of using generators

Disclaimer

  • This isn't meant to be an exhaustive tutorial on generators and related theory
  • Will be looking at a series of examples
  • I don't know if the code I've written is the "best" way to solve any of these problems.
  • Let's have a discussion

Part I

Introduction to Iterators and Generators

Iteration

  • As you know, Python has a "for" statement
  • You use it to iterate over a collection of items
>>> for x in [1,4,5,10]:
... print(x, end=' ')
...
1 4 5 10
>>>
  • And, as you have probably noticed, you can iterate over many different kinds of objects (not just lists)
Clone this wiki locally