generators

Introduction

В этой статье вы узнаете о том что такое генераторы в Python 3.

Создайте файл generators_demo.py и копируйте туда код из примеров.

Запустить файл можно командой python3 generators_demo.py

По объектам списка можно перемещаться разными способами. Если список небольшой - прекрасно подойдёт, например, функция enumerate

Генераторы нужны для больших объектов. Например, для таких, которые не помещаются в памяти.

Так как их невозможно загрузить целиком, обычные способы итерации не подходят и на помощь приходят генераторы.

Идея состоит в том, что особым образом передаётся только следующий элемент объекта - это называется lazy evaluation или ленивое вычисление

Ключевое слово, по которому можно опознать генератор в коде это yield

Генератор может включать в себя и обычные return но чтобы быть генератором нужен хотя бы один yield

def gen123(): yield 1 yield 2 yield 3 g = gen123() print(g) print(next(g)) print(next(g)) print(next(g)) print(next(g)) # нужно закомментировать чтобы код работал дальше

python generators_demo.py

<generator object gen123 at 0x01AADCD8> 1 2 3 Traceback (most recent call last): File "generators_demo.py", line 12, in print(next(g)) StopIteration

Каждый вызов функции-генератора создаёт новый генератор-объект (generator object)

h = gen123() i = gen123() print(h) print(i) print(h is i)

<generator object gen123 at 0x00F7DD48>
<generator object gen123 at 0x00F7DD80>
False

Соответственно и итерация по ним независимая

print(next(h)) print(next(h)) print(next(i))

1
2
1

def gen246(): print("About to yield 2") yield 2 print("About to yield 4") yield 4 print("About to yield 6") yield 6 print("About to return") g = gen246() print(next(g)) print(next(g)) print(next(g)) print(next(g))

python generators_demo.py

About to yield 2 2 About to yield 4 4 About to yield 6 6 About to return Traceback (most recent call last): File "generators_demo.py", line 43, in print(next(g)) StopIteration

Более сложные случаи применения генераторов рассмотрим в следующих статьях:

  1. Maintaining State in Generators

Article author: Andrei Olegovich

Похожие статьи
Interactive mode
str: strings
\: long line wrapping
Lists []
if, elif, else
Loops
Methods
Functions
*args **kwargs
enum
Get Variable Type
Testing with Python
Calling REST API with Python
Files: write, read, append, context manager…
Download File
SQLite3: database
datetime: Date and Time в Python
json.dumps
Selenium + Python
Issues with Python
DJANGO
Flask
ZPL printer script
socket :Python Sockets
Virtual Environment
subprocess: shell commands execution
multiprocessing
psutil: system usage
sys.argv: command prompt variables
PyCharm: IDE
pydantic: data validation
paramiko: SSH with Python
enumerate

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: