Skip to content

string values of given in value_error.const error messages are reported without enclosing quotes #4505

@DMRobertson

Description

@DMRobertson

Initial Checks

  • I have searched GitHub for a duplicate issue and I'm sure this is something new
  • I have searched Google & StackOverflow for a solution and couldn't find anything
  • I have read and followed the docs and still think this is a bug
  • I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like FastAPI or mypy)

Description

I noticed that strings are reported without enclosing quotes. This isn't a huge problem but it could cause confusion if given is a string which looks like str(x) for some non-string x. E.g. in the example below I get the same error message when given is the integer 123 and the string '123'.

I haven't looked at the source code, but I would guess there is a format string which ends up calling str(given) instead repr(given). I think I'd prefer the latter, though if given were a complicated object like a a long list or a heavily nested dictionary its repr(...) could be unwieldy.

Example Code

from pydantic import BaseModel, ValidationError
from typing import Literal

class Model(BaseModel):
    field: Literal["hello", "world"]

try:
    Model.parse_obj({"field": 123})
except ValidationError as e:
    print(e)
    # 1 validation error for Model
    # field
    #   unexpected value; permitted: 'hello', 'world' (type=value_error.const; given=123; permitted=('hello', 'world'))


try:
    Model.parse_obj({"field": "123"})
except ValidationError as e:
    print(e)
    # 1 validation error for Model
    # field
    #   unexpected value; permitted: 'hello', 'world' (type=value_error.const; given=123; permitted=('hello', 'world'))

Python, Pydantic & OS Version

pydantic version: 1.9.1
            pydantic compiled: True
                 install path: /home/dmr/.cache/pypoetry/virtualenvs/matrix-synapse-RhMlrixz-py3.10/lib64/python3.10/site-packages/pydantic
               python version: 3.10.6 (main, Aug  2 2022, 00:00:00) [GCC 12.1.1 20220507 (Red Hat 12.1.1-1)]
                     platform: Linux-5.18.18-200.fc36.x86_64-x86_64-with-glibc2.35
     optional deps. installed: ['typing-extensions'

Affected Components

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions