Skip to content

Conversation

@ROCKTAKEY
Copy link
Contributor

@ROCKTAKEY ROCKTAKEY commented May 14, 2025

Hello, thanks for your maintenance.

I fixed the constructor type of UnionField to accept not only Field but also subclass of Field, such as Serializer.

As described in Common issues and solutions / variance in mypy document, Dict[T, U] type does not accept subclass of U, while Mapping does. So I replace Dict with Mapping.

Example

The code below causes error by mypy. After applying this PR, it does NOT causes any error.

from dataclasses import dataclass

from rest_framework.fields import IntegerField

from rest_framework_dataclasses.fields import UnionField
from rest_framework_dataclasses.serializers import DataclassSerializer


@dataclass
class Example:
    x: int


class ExmapleSerializer(DataclassSerializer[Example]):
    class Meta:
        dataclass = Example


child_fields = {
    Example: ExmapleSerializer,
    int: IntegerField,
}

UnionField(child_fields=child_fields)
main.py:24: error: Argument "child_fields" to "UnionField" has incompatible type "dict[type, type]"; expected "dict[type, Field[Any, Any, Any, Any] | type[Field[Any, Any, Any, Any]]]"  [arg-type]
main.py:24: note: "Dict" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
main.py:24: note: Consider using "Mapping" instead, which is covariant in the value type
Found 1 error in 1 file (checked 1 source file)

@oxan oxan force-pushed the fix-union-field-type branch from c4ae5ce to ad82f6c Compare May 14, 2025 15:54
@oxan oxan merged commit 35b2e0c into oxan:master May 14, 2025
8 checks passed
@oxan
Copy link
Owner

oxan commented May 14, 2025

Thanks!

@ROCKTAKEY ROCKTAKEY deleted the fix-union-field-type branch May 14, 2025 16:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants