我正在使用 pydantic 来验证 Json/Dict 输入。但我还使用 mypy 来验证代码的类型完整性。
当使用该pydantic.constr类型(其中包括验证给定字符串是否遵循正则表达式)时,我收到 mypy 错误。
这是代码:
from typing import List
import pydantic
Regex = pydantic.constr(regex="[0-9a-z_]*")
class Data(pydantic.BaseModel):
regex: List[Regex]
data = Data(**{"regex":["abc", "123", "etc"]})
print(data, data.json())
Run Code Online (Sandbox Code Playgroud)
这是 mypy 的输出:
$ mypy main.py
main.py:9: error: Variable "main.Regex" is not valid as a type
main.py:9: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
Run Code Online (Sandbox Code Playgroud)
我检查了文档,但找不到处理此问题的方法。我知道我可以为该正则表达式创建一个静态类型,但这违背了 pydantic 的目的。我能通过的唯一方法是使用一个# type: ignore远非理想的方法。
那么有没有一种方法可以同时具有 pydantic 和 mypy 的优点来处理这个问题呢?
我想使用Python的结构模式匹配来区分元组(例如代表一个点)和元组列表。
但直接的方法不起作用:
def fn(p):
match p:
case (x, y):
print(f"single point: ({x}, {y})")
case [*points]:
print("list of points:")
for x, y in points:
print(f"({x}, {y})")
fn((1, 1))
fn([(1, 1), (2, 2)])
Run Code Online (Sandbox Code Playgroud)
其输出:
single point: (1, 1)
single point: ((1, 1), (2, 2))
Run Code Online (Sandbox Code Playgroud)
而我希望它输出:
single point: (1, 1)
list of points:
(1, 1)
(2, 2)
Run Code Online (Sandbox Code Playgroud)
切换 case 语句的顺序在这里也没有帮助。
通过模式匹配解决这个问题的好方法是什么?