SimpleCookie
is apparently a generic type and thus the following code (test.py) gives an error when checked with mypy
:
from http.cookies import SimpleCookie
cookie = SimpleCookie()
test.py:3: error: Need type annotation for 'cookie'
Now if I change test.py line 3 to:
cookie: SimpleCookie = SimpleCookie()
I get the following error:
test.py:3: error: Missing type parameters for generic type "SimpleCookie"
SimpleCookie
inherits from dict
, has str
keys and Morsel
values, so I'd assume that the correct generic type annotation is something like this:
from http.cookies import Morsel, SimpleCookie
cookie: SimpleCookie[str, Morsel] = SimpleCookie()
But now the error is:
test.py:3: error: "SimpleCookie" expects 1 type argument, but 2 given
Changing line 3 to
cookie: SimpleCookie[str] = SimpleCookie()
suddenly makes mypy
happy, but leaves me very confused why this is the correct solution, so I have two questions:
- Why is
SimpleCookie
a generic type with one argument? - What's the best way to handle this in my code? Should I annotate
SimpleCookie
variables withSimpleCookie[str]
(which seems like a lie to me) or should I just annotate them withAny
and hope this will be cleaned up in future Python versions?
mypy
version 0.750 and Python 3.8.0