Введение в Python
Теория: Python yield and iteration in depth
Полный доступ к материалам
Yield operator in Python
The problem
- Generator creates lazy seq, but...
- The syntax is difficult for long expressions
- Extra variables problem
Two ways
- Return generator from a function
- Use yield operator in a function
What is yield
- When yield inside a function, it returns generator
- Function evaluates only when iteration starts
- Yield returns a result as a generator element
- Yield stops function until the next iteration
- The function starts from the previous yield
Usage
Common rules
- The number of elements is equal to number if yields
- You can use yield with cycles
- raise StopIteration() to break immediately
- Other rules applied to generators are true
How does iteration work in depth
- Python never iterates the object itself
- Python forces an object into a generator (if possible)
- Iterate generator stands for calling gen.next() method
- (or next(gen) function in Py3)
- Catch StopIteration error, stop if it occurred
Why need iter
- Implement own iteration rules for...
- Databases, ORM
- Structed data (CSV, XML)
- Network resources
How does Python iterate a generator
Why need manual iteration?
- Perhaps you won't use it
- It's just an interface
- Some tricky situations
- itertools library