Skip to content

UUID validators with custom string object #1294

@fafanoulele

Description

@fafanoulele

Hi,

I use the Pydantic version 2.6.0.

When trying to validate an UUID from a customize string (the class _CustomizeStr in the code bellow), the validation fails (i.e. v.validate_python(_CustomizeStr('1fa79205-f747-465b-bf7a-cabc8ce60644'))) with the following error:

>       output = v.validate_python(_CustomizeStr('1fa79205-f747-465b-bf7a-cabc8ce60644'))
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for uuid
E         UUID input should be a string, bytes or UUID object [type=uuid_type, input_value=1fa79205-f747-465b-bf7a-cabc8ce60644, input_type=test_uuid_with_custom_string.<locals>._CustomizeStr]
E           For further information visit https://errors.pydantic.dev/latest/v/uuid_type

Whereas with Python UUID class, it is possible to create an UUID from a customize string i.e. UUID(_CustomizeStr('1fa79205-f747-465b-bf7a-cabc8ce60644')). So I would expect the same behaviour with Pydantic.

The test to highlight the issue I encounter:

def test_uuid_with_custom_string():
    class _CustomizeStr(str):
        def __init__(self, original_str: str):
            super(_CustomizeStr, self).__init__()
            self.__class__.__name__ = 'str'
            self._original_str = original_str

        def __str__(self) -> str:
            return self._original_str

        def __repr__(self) -> str:
            return self._original_str

    assert UUID('1fa79205-f747-465b-bf7a-cabc8ce60644') is not None
    assert UUID(_CustomizeStr('1fa79205-f747-465b-bf7a-cabc8ce60644')) is not None

    v = SchemaValidator({'type': 'uuid'})
    # The following line fails
    output = v.validate_python(_CustomizeStr('1fa79205-f747-465b-bf7a-cabc8ce60644'))
    assert output == UUID('1fa79205-f747-465b-bf7a-cabc8ce60644')
    assert isinstance(output, UUID)

To be honest, I am not sure it is valid to consider that as an issue. On my side, I've workaround the issue, but I wanted to bring up that to have your opinion. Feel free to close it if it is not a valid issue.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions