特化re.Patternto的型別re.Pattern[bytes],mypy正確檢測型別錯誤:
import re
REGEX: re.Pattern[bytes] = re.compile(b"\xab.{2}")
def check(pattern: str) -> bool:
if str == "xyz":
return REGEX.fullmatch(pattern) is not None
return True
print(check("abcd"))
檢測到型別不匹配:
$ mypy ~/main.py
/home/oren/main.py:5: error: Argument 1 to "fullmatch" of "Pattern" has incompatible type "str"; expected "bytes"
Found 1 error in 1 file (checked 1 source file)
但是,當我嘗試實際運行代碼時,我收到一條奇怪的 (?) 訊息:
$ python ~/main.py
Traceback (most recent call last):
File "/home/oren/main.py", line 2, in <module>
REGEX: re.Pattern[bytes] = re.compile(b"\xab.{2}")
TypeError: 'type' object is not subscriptable
為什么型別注釋會困擾 Python?
uj5u.com熱心網友回復:
在 Python 3.9 中添加了使用or來專門化泛型re.Pattern和re.Match型別的能力。看來您使用的是較舊的 Python 版本。[str][bytes]
對于 3.8 之前的 Python 版本,該typing模塊提供了一個typing.re命名空間,其中包含用于此目的的替換型別。
從 Python 3.8 開始,它們在typing模塊中直接可用,并且typing.re不推薦使用命名空間(將在 Python 3.12 中洗掉)。
參考:https ://docs.python.org/3/library/typing.html#typing.Pattern
概括:
- 對于 Python <3.8,使用
typing.re.Pattern[bytes] - 對于 Python 3.8,使用
typing.Pattern[bytes] - 對于 Python 3.9 ,使用
re.Pattern[bytes]
uj5u.com熱心網友回復:
您是否嘗試使用typing模塊?我認為這里出現問題是因為re.Pattern[bytes]無法像您想要的那樣使用運算式。嘗試類似的東西typing.re.Pattern[bytes]。
我在 python3.7 上檢查了它,它可以作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420835.html
標籤:
上一篇:正則運算式可變長度
