pythondjangopython-typingpylancepyright

How to resolve type checking error in Django when accessing Serializer.validated_data


I'm encountering a type checking error in VSCode with Pylance (pyright) when accessing serializer.validated_data["code"] in a Django project. The errors are:

The property type is inferred as:
(property) validated_data: empty | Unknown | dict[Unknown, Unknown] | Any | None

VSCode settings:

"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic"

I've defined the serializer class like,

class InputSerializer(BaseSerializer):
        code = serializers.CharField(
            required=True,
            max_length=255,
            validators=[voucher_code_validator],
        )

How can I fix this?


Solution

  • This depends a bit on the stubs you are using. With (mypy) https://github.com/typeddjango/djangorestframework-stubs you should not get that error as validated_data is typed as Any. I would think there could be an equivalent for pyright (which Pylance uses).

    With other (no?) stubs there are multiple possibilities, i.e. the ones you have listed empty | Unknown | dict[Unknown, Unknown] | Any | None. To satisfy a type-checker you have to handle empty | None. You could for example add these lines:

    assert serializer.validated_data is not None
    assert serializer.validate_data is not empty # import from fields
    

    OR you assure that you indeed have a dict here:

    assert isinstance(serializer.validated_data, dict)
    

    Alternatives: