Constructs

Contents

Constructs#

This page focuses on terms that are implemented to python and allows you to explore its syntax.

Iterator#

An iterator is an object that implements the iterator protocol.

The iterator protocol suggests that an object have the following:

  • The __iter__ dunder that returns object with a __next__ dunder.

  • The __next__ dunder is supposed to return the elements of the iterator one by one and raise a StopIteration exception when there are no more elements to iterate.

Check details on the iterator.


Probably the most representive example of the iterator is a regular python list. The following cells show that the descripted iterator protcol is fair for the iterator.

The iter function can be applied to the list, showing that the __iter__ dunder is implemented for list.

lst = [1, 2]
lst_iterator = lst.__iter__()
lst_iterator
<list_iterator at 0x71db0e506c80>

The __iter__ dunder should also return an iterator. This could be the same object, or something else as in the list case. A list_iterator instance is returned.

The following cell shows that the list_iterator has an __iter__ dunder as well. However, the dunder returns the object itself.

lst_iterator is lst_iterator.__iter__()
True

The list_iterator has a __next__ dunder. For each call, it returns the corresponding element of the list from which the list_iterator comes.

(lst_iterator.__next__(), lst_iterator.__next__())
(1, 2)

When there are no longer any corresponding elements - the StopIteration error will be raised.

next(lst_iterator)
---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

Cell In[84], line 1

----> 1 next(lst_iterator)



StopIteration: 

Data class#

There is a special tool in Python called dataclasses. Dataclasses allow you to build classes that store data and provide some built-in tools for operating with them. The crusial features are:

  • Automatically generated __init__ that will create all required attributes.

  • Converting to string as __repr__ method will be defined in dataclass.

  • Comparing as __eq__ method will be implemented.

Find out more in the special page.


To define a dataclass, you have to use the dataclasses.dataclass decorator. The following cell defines one that we’ll use:

from dataclasses import dataclass

@dataclass
class SomeData:
    value1: int
    value2: str

Any instance of such a class can be transformed into a string in the format <ClassName>(<attr1>=<val1>, ...). The following cell shows this:

print(SomeData(1, "wow"))
SomeData(value1=1, value2='wow')

You can compare dataclasses out of the box, and if their attributes have the same values, you will find that the instances are equal.

print(SomeData(1, "wow") == SomeData(1, "wow"))
print(SomeData(1, "wow") == SomeData(2, "oh my gosh"))
True
False