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:
"__getitem__" method not defined on type "empty" Pylance
Object of type "None" is not subscriptable Pylance
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?
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:
"__getitem__" method not defined on type "empty" Pylance
Object of type "None" is not subscriptable Pylance
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?
Share Improve this question edited Mar 13 at 15:13 Daraan 4,2427 gold badges22 silver badges47 bronze badges asked Mar 11 at 9:35 FarhadFarhad 3361 gold badge2 silver badges16 bronze badges 1 |1 Answer
Reset to default 1This depends a bit on the stubs you are using. With (mypy) https://github/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:
- write your own
validated_data
property with a more precise return type (and possible checks). - Unsafe but fastest way: Use
typing.cast
serializer.validated_data.get("product")
the error is: "Argument of type "Unknown | Any | None" cannot be assigned to parameter". – Farhad Commented Mar 11 at 11:58