Skip to content

UUID typing hints of Pydantic 1.8 are inaccurate #2418

@allezxandre

Description

@allezxandre

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this is a bug

Bug

It appears commit 7da04d9 introduces a type erasure on UUID1/UUID2/UUID3/UUID4 that makes them all Union[UUID, str], losing the strict inheritance from UUID.

Now:

from uuid import UUID, uuid4
from pydantic import UUID4, BaseModel

def expects_any_uuid(arg: UUID):
    pass

class MyModel(BaseModel):
    my_uuid: UUID4


# While these two are now correct in regards to type checking:
# (they were triggering typing errors in v1.7)
MyModel(my_uuid=uuid4())                                 # 1
MyModel(my_uuid="5259A9AA-D1FD-4D0A-B17D-87803904C233")  # 2

# These two calls are not correct anymore:
expects_any_uuid(MyModel(my_uuid=uuid4()).my_uuid)       # 3
expects_any_uuid(uuid4())                                # 4
# Type checking like MyPy would say something along the following:
#   Argument 1 to "expects_any_uuid" has incompatible type "Union[UUID, str]"; expected "UUID"

I would argue that making # 2 clear the typing error from 1.7 is nice to have, but we could already use something like a # type: ignore comment to explicitly tell type-checking, which was acceptable since some strs are not UUID4s, and as such it makes sense to have to explicitly silent a warning here.

Same with # 1, since its type is “erased” to a generic UUID, we would need to check again that it is indeed a v4 UUID.

On the other hand, a UUID4 is always a UUID, so # 3 and # 4 should never trigger a static typing error.

I don't have a solution to make all examples # 1 to # 4 from above work, so instead I'm opening an issue here in hopes someone would have a solution.


Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.8
            pydantic compiled: True
                 install path: <redacted>/venv/lib/python3.9/site-packages/pydantic
               python version: 3.9.2 (default, Feb 19 2021, 17:43:04)  [Clang 12.0.0 (clang-1200.0.32.29)]
                     platform: macOS-11.2.1-x86_64-i386-64bit
     optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions']

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions