[Python] How can mypy accept pydantic's constr() types?

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have this code:

    from pydantic import BaseModel, constr

    DeptNumber = constr(min_length=6, max_length=6)

    class MyStuff(BaseModel):
    dept: DeptNumber

    ms = MyStuff(dept = "123456")


    deptnr.py:6: error: Variable "deptnr.DeptNumber" is not valid as a type
    deptnr.py:6: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
    ​

    The provided link doesn't seem to really address my problem (I'm not using Type).

    This happens with or without this mypy.ini:

    [mypy]
    plugins = pydantic.mypy

    [pydantic-mypy]
    init_typed = true


    Initially I also had that error in a Pydantic choice as below, but I got around that by using Python's Literal instead.

    DIR = choice(["North", "East", "South", "West"])


    What do I need to change to make mypy happy with my Pydantic constr?

    Continue reading...

Compartilhe esta Página