Ago*_*iro 7 python mypy python-3.8
SimpleCookie显然是通用类型,因此以下代码(test.py)在检查时会出错mypy:
from http.cookies import SimpleCookie
cookie = SimpleCookie()
Run Code Online (Sandbox Code Playgroud)
test.py:3: 错误:“cookie”需要类型注释
现在,如果我将 test.py 第 3 行更改为:
cookie: SimpleCookie = SimpleCookie()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
test.py:3: 错误:缺少泛型类型“SimpleCookie”的类型参数
SimpleCookie继承自dict, 有str键和Morsel值,所以我假设正确的泛型类型注释是这样的:
from http.cookies import Morsel, SimpleCookie
cookie: SimpleCookie[str, Morsel] = SimpleCookie()
Run Code Online (Sandbox Code Playgroud)
但现在错误是:
test.py:3: 错误:“SimpleCookie”需要 1 个类型参数,但给出 2 个
将第 3 行更改为
cookie: SimpleCookie[str] = SimpleCookie()
Run Code Online (Sandbox Code Playgroud)
突然mypy很高兴,但让我很困惑为什么这是正确的解决方案,所以我有两个问题:
SimpleCookie泛型类型只有一个参数?SimpleCookie用SimpleCookie[str](这对我来说似乎是个谎言)来注释变量,还是应该只用注释来注释它们Any并希望这会在未来的 Python 版本中得到清理?mypy 版本 0.750 和 Python 3.8.0
str在SimpleCookie[str]实际上指的是类型_T的coded_value中Morsel。
mypy使用https://github.com/python/typeshed/blob/master/stdlib/3/http/cookies.pyi:
class Morsel(Dict[str, Any], Generic[_T]):
value: str
coded_value: _T
key: str
def set(self, key: str, val: str, coded_val: _T) -> None: ...
# ...
class BaseCookie(Dict[str, Morsel[_T]], Generic[_T]):
# ...
def value_decode(self, val: str) -> _T: ...
def value_encode(self, val: _T) -> str: ...
# ...
def __setitem__(self, key: str, value: Union[str, Morsel[_T]]) -> None: ...
class SimpleCookie(BaseCookie[_T], Generic[_T]): ...
Run Code Online (Sandbox Code Playgroud)
_T应该是Any,即SimpleCookie[Any],如python/typeshed#3060 中所述:
Morsel 确实将任何值转换为字符串...... max-age 可以采用整数(unix 时间)和 http-only 一个布尔值。
实际上,我无法重现您遇到的错误:
from http.cookies import SimpleCookie
cookie: SimpleCookie = SimpleCookie()
Run Code Online (Sandbox Code Playgroud)