User defined types

Types are defined by supported operations - Fluent Python, 2nd Edition

Here we assume that type is a set of values and a set of functions that one can apply to these values. PEP 483—The Theory of Type Hints”

How can we make sure that the operation is supported?

Understanding duck-typing

Take the object and perform the required action as soon as possible.

Duck typing to handle a string or an iterable of strings - Fluent Python, 2nd Edition

try:
    """Do something as one expected type"""
except AttributeError:
    pass
"""Try to use it as another type"""

Here is one example: when you write code that accepts a sequence of items to process internally as a list, don’t enforce a list argument by type checking. Instead, take the argument and immediately build a list from it” - Fluent Python

Consider User* variants of built-in types

There is a chance that you find a suitable built-in class with small modifications.

>>> from collections import UserDict

>>> class UpperCaseDict(UserDict):
...     def __setitem__(self, key, value):
...         key = key.upper()
...         super().__setitem__(key, value)
...

Read more about inherting directly from dict.

Recipe: Type hints from built-in ABC

Recipe: If your action goes deeper, consider static protocols

To sort any object, we have to make sure that the type is consistent-with a protocol.

sorted uses the < operator - Fluent Python, 2nd Edition

LT = TypeVar('LT', bound=SupportsLessThan)
#python