app/notes/20220528-2006.md
Python Generic Type Annotations
python-generic-type-annotations
1653768360
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](https://peps.python.org/pep-0563/):
`from __future__ import annotations`.
A working example that passes both strict mypy typing and is syntactically
correct:
```python
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()
```