我一直在尝试输入
re.compile
的返回值,但 mypy 总是抱怨,即使我使用了 VS Code 建议的确切返回类型,即 re.Pattern[re.AnyStr@compile]
重新编译的签名:
(function) def compile(
pattern: AnyStr@compile,
flags: _FlagsType = 0
) -> Pattern[AnyStr@compile]
我的代码:
import re
# from typing import Pattern
def dummyF(fp: str)-> dict[str, int]:
# ...
daterx : re.Pattern[re.AnyStr@compile] = re.compile(r""" ...
""", re.VERBOSE)
# ...
还有 mypy 投诉
$pdm run startmypy
src/regex-log-filtering.py:20: error: Invalid type comment or annotation [valid-type]
Found 1 error in 1 file (checked 8 source files)
那么注释这个例子的正确方法是什么?
我试过了
daterx : re.Pattern[re.AnyStr] = re.compile(r"""
daterx : re.Pattern[typing.AnyStr] = re.compile(r"""
后面的例子让我非常震惊,因为这个错误对我来说甚至没有什么意义。
$pdm run startmypy
src/regex-log-filtering.py:21: error: Type variable "typing.AnyStr" is unbound [valid-type]
src/regex-log-filtering.py:21: note: (Hint: Use "Generic[AnyStr]" or "Protocol[AnyStr]" base class to bind "AnyStr" inside a class)
src/regex-log-filtering.py:21: note: (Hint: Use "AnyStr" in function signature to bind "AnyStr" inside a function)
我不知道VSCode究竟在做什么,但
AnyStr@compile
是语法错误;这似乎是某种内部表示,作为有效类型提示被泄露。
根据文档,AnyStr
是类型变量,而不是类型:
是一个约束类型变量,定义为AnyStr
.AnyStr = TypeVar('AnyStr', str, bytes)
这确保了关于
re.compile
的两件事。
pattern
参数只能是 str
或 bytes
值(或任一子类的实例)。Pattern
。如果你提供一个str
模式,你会得到一个Pattern[str]
值。如果你提供一个bytes
值,你会得到一个Pattern[bytes]
值。对于您的作业,您正在将
str
值传递给 re.compile
,因此您应该期望得到一个 Pattern[str]
值。
daterx : re.Pattern[str] = re.compile(r""" ...""", re.VERBOSE)