News for hackers. Stuff that matters.
Re:Static Duck Typing in Python with Protocols by chriswarbo on Tuesday November 23, 2021 @06:12AM (#29316501)
Sounds like you want 'newtypes', e.g.

    XCoord = NewType("XCoord", int)
    YCoord = NewType("YCoord", int)
    Point = NewType("Point", Tuple[XCoord, YCoord])
These are just new names for existing types (in this case the existing types `int` and `Tuple[int, int]`); they make no difference to the way the code actually runs (unlike, say, introducing a new class).

However, checkers like Mypy will not let us mix up these newtypes with their underlying types. For example, if a function requires a `Point`, Mypy will complain if we try to call it with a `Tuple[int, int]`.

Newtypes are useful for keeping semantically-distinct types separate, even if they just-so-happen to use the same underlying implementation. In other words, they let us selectively avoid duck-typing if it might cause problems.

Of course, this is only useful if the code we're calling actually exposes such types!

There are no comments on this comment yet.