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

3

18

I use in Python the package pydantic and the linker Flake8. I want to use constr from pydantic with a regular Experssion. Only certain Characters should be passed. (a-z, A-Z, 0-9 and _)

The regular Experssion "^[a-zA-Z0-9_]*$" works, but flake8 shows me the following error:

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_]*$") = ""

Can you help me to avoid the Error Message?

Frederique answered 19/11, 2020 at 10:33 Comment(0)
H
24

the error here comes from pyflakes which attempts to interpret type annotations as type annotations according to PEP 484

the annotations used by pydantic are incompatible with PEP 484 and result in that error. you can read more about this in this pyflakes issue

I'd suggest either (1) finding a way to use pydantic which doesn't involve violating PEP 484 or (2) ignoring the errors from pyflakes using flake8's extend-ignore / # noqa: ... / per-file-ignores


disclaimer: I am one of the pyflakes maintainers and I am the current flake8 maintainer

Hollow answered 19/11, 2020 at 18:6 Comment(0)
I
4

You can extract the constr(..) statement to a separate variable:


KeyTypeStr = constr(regex="^[a-zA-Z0-9_]*$")
KeyOutputStr = constr(regex="^[a-zA-Z0-9_]*$")

class RedisSettings(BaseModel):
    keyInput: KeyTypeStr = "" 
    keyOutput: KeyOutputStr = ""

It looks even cleaner like that, and the type annotation can be reused easily, even in other modules.

Illiterate answered 4/8, 2022 at 11:35 Comment(0)
H
0

Follow:

How about:

from typing import Annotated

from pydantic import BaseModel, Field


class RedisSettings(BaseModel):
    keyInput: Annotated[str, Field(regex=r"^\w*$")] = ""
    keyOutput: Annotated[str, Field(regex=r"^\w*$")] = ""
Haug answered 12/4, 2023 at 4:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.