flake8 和 Pydantic 约束类型的语法错误:constr(regex=)

Syntax Error with flake8 and Pydantic Constrained Types: constr(regex=)

我在 Python 中使用了包 pydantic 和链接器 Flake8。我想将来自 pydantic 的 constr 与常规 Experssion 一起使用。只应传递某些字符。 (a-z、A-Z、0-9 和 _)

常规 Experssion "^[a-zA-Z0-9_]*$" 有效,但 flake8 显示以下错误:

syntax error in forward annotation '^[a-zA-Z0-9_]*$' flake8(F722)

class RedisSettings(BaseModel):
    keyInput: constr(regex="^[a-zA-Z0-9_]*$") = "" 
    keyOutput: constr(regex="^[a-zA-Z0-9_]*$") = ""

你能帮我避免错误消息吗?

这里的错误来自 pyflakes,它试图根据 PEP 484

将类型注释解释为类型注释

pydantic 使用的注释与 PEP 484 不兼容并导致该错误。你可以阅读更多关于这个 in this pyflakes issue

我建议 (1) 找到一种使用 pydantic 的方法,它不涉及违反 PEP 484 或 (2) 使用 flake8 的 extend-ignore / # noqa: ... / 忽略来自 pyflakes 的错误per-file-ignores


免责声明:我是 pyflakes 维护者之一,我是当前的 flake8 维护者