Skip to content

Throw descriptive exception for incorrectly defined validator fields. #3215

@SunsetOrange

Description

@SunsetOrange

Discussed in #3129

Originally posted by SunsetOrange August 24, 2021
I had been trying to locate a bug in my code for an hour or so, which I eventually narrowed down to an incorrectly defined custom validator decorator. I had placed multiple field strings into the decorator call, inside a list rather than as multiple args.

My own mistake, but Pydantic had been throwing a very unhelpful exception stating that my model was not hashable.
The exception was pointing at the class definition line, not the validator decorator.

Exception has occurred: TypeError unhashable type: 'list'

This confused me greatly for a good while as I tried to find a possible location in the model and its super classes where a list was being used as a dictionary key. As this is a mistake that others could easily make (and I think I have made it in the past as well), it would be nice and helpful to output an exception that identifies the mistake and provides helpful feedback. Else wise, the source of the exception is difficult to identify.

I proposing that the following code be added to class_validators.py at line 75.

    elif not all([isinstance(field, str) for field in fields]):
        raise ConfigError(
            "validator fields should be passed as separate string args. Do not pass multiple fields as a list, etc. "
            "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)` "
            "NOT `@validator(['<field_name_1>', '<field_name_2>', ...], ...)`"
        )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions