Ducks and protocols

Custom collections

We’ve talked about dunder methods and we’ve talked about different types of iterables.

If an object implements the dunder methods that allow it to be iterable, indexable, and have a length, we call that object a sequence.

class Fibonacci:

    def __init__(self, n=100):
        self.n = n

    def __iter__(self):
        a, b = 0, 1
        for _ in range(self.n):
            yield a
            a, b = b, a + b

    def __getitem__(self, n):
        if n < 0:
            n += self.n
        if n < 0 or n >= self.n:
            raise IndexError("Index out of range")
        # NOTE: this could be more efficient with a closed-form solution
        if n == 0 or n == 1:
              return 1
        return self[n-1] + self[n-2]

    def __len__(self):
        return self.n

If an object implements the dunder methods that make it act like dictionary, regardless of whether it can be mutated, we call it a mapping.

class SequenceWrapperMapping:

    """Makes a sequence act like a mapping (using indexes as keys)."""

    def __init__(self, sequence):
        self.sequence = sequence

    def __len__(self):
        return len(self.sequence)

    def __iter__(self):
        yield from range(len(self))

    def __getitem__(self, key):
        if key not in range(len(self)):
            raise KeyError(key)
        return self.sequence[key]

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        return 0 <= key < len(self)

    def keys(self):
        return dict.fromkeys(self).keys()

    def items(self):
        return dict.fromkeys(self).items()

    def values(self):
        return dict.fromkeys(self).values()

    def __eq__(self, other):
        if not isinstance(other, SequenceWrapperMapping):
            return NotImplemented
        return self.items() == other.items()

    def __repr__(self):
        return f"{type(self).__name__}({self.sequence!r})"

Protocols

We like to use nouns to describe verbs in Python. Sometimes it’s one verb or sometimes it’s a bundle of them.

An iterable is a noun that describes an object that supports one specific action: iteration.

An callable is a noun that describes an object that supports one specific action: calling.

Sequences and mappings are nouns that describe objects which support a group of specific actions.

In Python, we often use the word protocol to describe these nouns-that-describe verbs.

The iterator protocol describes how for loops interact with the objects they loop over. The sequence protocol describes the behaviors we expect sequence-like objects to implement. The context manager protocol describes the behaviors that context managers need to implement.

Some of Python’s other protocols are file-like objects, path-like objects, and hashable objects.

The word interface is sometimes used as a synonym to the word protocol, although interfaces in languages like Java are more strict than Python’s protocols.

Duck typing

Why do we like noun-describing-verbs so much?

Duck typing.

Duck typing is the idea that we care about specific object behaviors much more than we care about an object’s type.

We say:

If it looks like a duck, walks like a duck, and quacks like a duck, then it’s a duck.

Instead of caring whether an object is a list, we care that it’s a sequence or maybe simply that it’s an iterable.

When we type check

Where do we strongly check the types of objects in Python? Is duck typing used everywhere?

Duck typing is used very often in Python, but there are some places in Python where strong type checking tends to be used instead.

Using a try/except block in Python will check the type of the exception:

try:
    4 / 0
except ZeroDivisionError as e:
    print("The exception type was:", type(e))

A bit ironically, dunder methods for operators tend to perform type checks as well. For example, here’s an implementation of equality checks (the == operator) on Counter objects from Python’s collections module:

def __eq__(self, other):
    'True if all counts agree. Missing counts are treated as zero.'
    if not isinstance(other, Counter):
        return NotImplemented
    return all(self[e] == other[e] for c in (self, other) for e in c)

Returning NotImplemented tells Python that in a x == y expression, the right-hand object should be checked for a valid equality method as well. You can think of NotImplemented as a way for an object to say “ask someone else because I don’t know how to do this”.

This allows a new object to extend the behavior of operators with an existing object. That means there’s not much downside to using strong type-checking within dunder methods!

It’s also common to see Python’s type function used to get an object’s class for the purpose of implementing a __repr__ method: For example here’s an implementation of __repr__ for asyncio.queues.Queue:

def __repr__(self):
    return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'

Goose typing

We have a function where users often accidentally pass non-iterables into it even though we expect an iterable object:

>>> def all_same(items):
...     for first in items:
...         break
...     for item in items:
...         if item != first:
...             return False
...     return True
...
>>> numbers = [2, 2, 2, 1, 2, 2]
>>> all_same(numbers)
False
>>> all_same(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in all_same
TypeError: 'int' object is not iterable

We could use exception handling and stick our for loop in a try block:

>>> def all_same(items):
...     try:
...         for first in items:
...             break
...     except TypeError:
...         raise TypeError("Argument must be iterable") from None
...     for item in items:
...         if item != first:
...             return False
...     return True
...
>>> numbers = [2, 2, 2, 1, 2, 2]
>>> all_same(numbers)
False
>>> all_same(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in all_same
TypeError: Argument must be iterable

But that feels a bit awkward, since our whole function body is now in that try block.

What if we checked for common iterable types using isinstance instead?

>>> def all_same(items):
...     if not isinstance(items, (list, tuple, set, str, bytes)):
...         raise TypeError("Argument must be iterable")
...     for first in items:
...         break
...     for item in items:
...         if item != first:
...             return False
...     return True
...
>>> numbers = [2, 2, 2, 1, 2, 2]
>>> all_same(numbers)
False
>>> all_same(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in all_same
TypeError: Argument must be iterable

This has the downside that any other iterable type that exists in Python wouldn’t work with this function.

>>> all_same(range(5))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in all_same
TypeError: Argument must be iterable

We’re not embracing duck typing anymore this way.

Python has a collections.abc module which contains a class called Iterable.

The list class does not inherit from the Iterable class, which we can see from looking at the list class’s base classes:

>>> list.mro()
[<class 'list'>, <class 'object'>]

What if we checked whether a list is an instance of collections.abc.Iterable?

>>> from collections.abc import Iterable
>>> numbers = [2, 2, 2, 1, 2, 2]
>>> isinstance(numbers, Iterable)
True

That says that a list object is an instance of this class!

If we check whether list is a subclass of Iterable, we’ll also see that it is… even though list doesn’t actually inherit from it:

>>> issubclass(list, Iterable)
True

What’s going on here?

Well, isinstance and issubclass are overloadable using dunder methods on a class’s metaclass.

>>> Iterable.__instancecheck__(numbers)
True
>>> Iterable.__subclasscheck__(list)
True

An object’s type is its class. A class’s type is its metaclass. We won’t get into metaclasses because they come up rarely, but that’s how the Iterable class is able to customize what isinstance and issubclass return.

The Iterable class returns True for isinstance or issubclass on any object that implements a __iter__ method:

>>> from collections.abc import Iterable
>>> class TwoByTwo:
...     def __iter__(self):
...         return iter((2, 2))
...
>>> issubclass(TwoByTwo, Iterable)
True
>>> a = TwoByTwo()
>>> isinstance(a, Iterable)
True

Instead of manually checking whether an object implements specific behaviors or trying to use specific behaviors and catching an exception, we can simply ask an “abstract base class” (like Iterable) whether the correct behaviors are implemented.

This ability for a class to extend the functionality of instance and subclass checks is sometimes referred to as goose typing.

So going back to our function, we could check whether the given input isn’t an Iterable object and then raise a custom exception in that case.

>>> from collections.abc import Iterable
>>> def all_same(items):
...     if not isinstance(items, Iterable):
...         raise TypeError("Argument must be iterable")
...     for first in items:
...         break
...     for item in items:
...         if item != first:
...             return False
...     return True
...

Our all_sum function will now work with other types of iterables that we didn’t think of:

>>> all_same(range(5))
False

Slippery ducks

So duck typing is just about not type checking in your own code, right?

Well, not quite. It’s actually more important to understand that the tools we use in Python often practice duck typing and that we can use that fact to our own benefit.

For example, many conversions to lists are unnecessary in Python.

Here we’re converting a string to a list to get all the characters in the string and then we’re using the string join method to put a space between each character:

>>> string = "letters"
>>> characters = list(string)
>>> " ".join(characters)
'l e t t e r s'

But we don’t need that list conversion because the string join method accepts any iterable that contains strings and strings are iterables that give us strings as we loop over them:

>>> string = "letters"
>>> " ".join(string)
'l e t t e r s'

Abstract base classes

If you want to implement a specific Python protocol yourself, look into the abstract base classes in Python’s collections.abc module.

You don’t need to inherit from them, but they’re handy for ensuring you implement the protocol completely.

Protocol Exercises

These exercises are all in the protocols.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:

$ python test.py swap_ends

X marks the spot

The following code is failing the tests. Figure out why the code is failing and then fix it:

def words_containing(words, letter):
    """Return all words that contain the given letter."""
    matching_words = []
    for word in words:
        if letter in word.lower():
            matching_words += word
    return matching_words

The code should work like this:

>>> from protocols import words_containing
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'y')
['My', 'my']
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'i')
['life', 'is']
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'm')
['My', 'my', 'message']

Convert from CSV Data

The from_csv accepts a string of CSV data and converts it into a list of lists.

It works like this:

>>> from protocols import from_csv
>>> text = 'purple,0.15\ncrimson red,0.30\nindigo,0.25\nsky blue,0.05\nspring green,0.25\n'
>>> from_csv(text)
[['purple', '0.15'], ['crimson red', '0.30'], ['indigo', '0.25'], ['sky blue', '0.05'], ['spring green', '0.25']]
>>> from_csv('purple,0.15')
[['purple', '0.15']]
>>> from_csv('')
[]

The current implementation of this function uses a temporary file to store the CSV data:

import csv
from tempfile import NamedTemporaryFile


def from_csv(csv_data):
    """Convert string of CSV data to list of lists"""
    with NamedTemporaryFile(mode="wt+") as csv_file:
        csv_file.write(csv_data)
        csv_file.seek(0)
        return list(csv.reader(csv_file))

Refactor this function so that it doesn’t use a temporary file.

Convert to CSV Data

The to_csv function accepts an iterable-of-iterables and converts it into a string of CSV data.

It works like this:

>>> from protocols import to_csv
>>> iterable_data = [['purple', '0.15'], ['crimson red', '0.30'], ['indigo', '0.25'], ['sky blue', '0.05'], ['spring green', '0.25']]
>>> to_csv(iterable_data)
'purple,0.15\r\ncrimson red,0.30\r\nindigo,0.25\r\nsky blue,0.05\r\nspring green,0.25\r\n'

The current implementation of this function uses a temporary file to store the CSV data:

import csv


def to_csv(rows):
    """Convert iterable-of-iterables to string of CSV data"""
    with NamedTemporaryFile(mode="wt+") as csv_file:
        writer = csv.writer(csv_file)
        writer.writerows(rows)
        csv_file.seek(0)
        return csv_file.read()

Refactor this function so that it doesn’t use a temporary file.

Sum Timestamps

The sum_timestamps function takes a list of timestamp strings of “minute:seconds”, and returns a “minute:seconds” timestamp string that represents the total time from the list of timestamps.

>>> from protocols import sum_timestamps
>>> times = ["1:10", "0:12", "4:03", "2:45"]
>>> sum_timestamps(times)
'8:10'
>>> times = ["0:55", "0:55", "0:55", "0:55", "0:55"]
>>> sum_timestamps(times)
'4:35'
>>> sum_timestamps(["0:00"])
'0:00'

Here’s the current implementation of sum_timestamps, which uses parse_time and format_time helper functions:

def parse_time(time_string):
    """Return total seconds from string of minutes:seconds."""
    sections = time_string.split(':')
    return int(sections[0]) * 60 + int(sections[1])

def format_time(seconds):
    """Return a minutes:seconds string based on input seconds."""
    sections = divmod(seconds, 60)
    return f"{sections[0]}:{sections[1]:02d}"

def sum_timestamps(timestamps):
    """Return a timestamp that represents the sum of the input timestamps."""
    total_seconds = [
        parse_time(time)
        for time in timestamps
    ]
    return format_time(sum(total_seconds))

Refactor the sum_timestamps function so that it doesn’t require a temporary list.

Hint

Use a generator expression.