Advanced syntax
It is hard to objectively tell which element of language syntax is advanced. For the purpose of this chapter on advanced syntax elements, we will consider the elements that do not directly relate to any specific built-in datatypes and which are relatively hard to grasp at the beginning. The most common Python features that may be hard to understand are:
- Iterators
- Generators
- Decorators
- Context managers
Iterators
An iterator is nothing more than a container object that implements the iterator protocol. It is based on two methods:
__next__
: This returns the next item of the container__iter__
: This returns the iterator itself
Iterators can be created from a sequence using the iter
built-in function. Consider the following example:
>>> i = ...
Get Expert Python Programming - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.