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 = iter('abc') >>> next(i) 'a' >>> next(i) 'b' >>> next(i) 'c' >>> next(i) Traceback (most recent call last): File "<input>", line 1, in <module>...