Notes

Python Generic Type Annotations

May 28, 2022

There’s a minor conflict within Python where mypy’s strict typing is incompatible with its current default syntax. Specifically, if you have a generic type like _TemporaryFileWrapper, mypy will tell you to add type parameters which will convert it to something like _TemporaryFileWrapper[bytes]. However, python 3 syntax will error out with a TypeError: 'type' object is not subscriptable. This can be fixed by importing the annotations future: from __future__ import annotations.

A working example that passes both strict mypy typing and is syntactically correct:

from __future__ import annotations

import tempfile


def get_tempfile() -> tempfile._TemporaryFileWrapper[bytes]:
    return tempfile.NamedTemporaryFile()


temp = get_tempfile()
with open(temp.name, 'wb') as f:
    f.write(b'data')
temp.close()