Skip to content

Commit 9f0ef04

Browse files
author
Diego Argueta
committed
Better documentation for new feature, fix tests
1 parent f34774e commit 9f0ef04

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

changelog.d/140.change.rst

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,30 @@
1-
It is now possible to use type-variant generics in your dataclasses, such as ``Sequence`` or ``MutableSequence`` instead of ``List``, ``Mapping`` instead of ``Dict``, etc.
1+
It is now possible to use `type-variant generics`_ in your dataclasses, such as ``Sequence``
2+
or ``MutableSequence`` instead of ``List``, ``Mapping`` instead of ``Dict``, etc.
23

3-
This doesn't change any behavior by Desert or Marshmallow. Rather, the primary benefit is getting more flexibility from type checkers. For example, by using ``Mapping`` or ``MutableMapping``, users can pass ``OrderedDict`` to an attribute without MyPy complaining.
4+
This allows you to hide implementation details from users of your dataclasses. If a field
5+
in your dataclass works just as fine with a tuple as a list, you no longer need to force
6+
your users to pass in a ``list`` just to satisfy type checkers.
7+
8+
For example, by using ``Mapping`` or ``MutableMapping``, users can pass ``OrderedDict`` to
9+
a ``Dict`` attribute without MyPy complaining.
10+
11+
.. code-block:: python
12+
13+
@dataclass
14+
class OldWay:
15+
str_list: List[str]
16+
num_map: Dict[str, float]
17+
18+
19+
# MyPy will reject this even though Marshmallow works just fine. If you use
20+
# type-variant generics, MyPy will accept this code.
21+
instance = OldClass([], collections.ChainMap(MY_DEFAULTS))
22+
23+
24+
@dataclass
25+
class NewWay:
26+
str_list: List[str] # Type-invariants still work
27+
num_map: MutableMapping[str, float] # Now generics do too
28+
29+
30+
.. _type-variant generics: https://mypy.readthedocs.io/en/stable/generics.html

tests/test_make.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -525,12 +525,19 @@ class A:
525525
desert.schema_class(A)
526526

527527

528+
T = t.TypeVar("T")
529+
530+
531+
class UnknownGeneric(t.Generic[T]):
532+
pass
533+
534+
528535
def test_raise_unknown_generic(module: DataclassModule) -> None:
529536
"""Raise UnknownType for unknown generics."""
530537

531538
@module.dataclass
532539
class A:
533-
x: t.Iterable[int]
540+
x: UnknownGeneric[int]
534541

535542
with pytest.raises(desert.exceptions.UnknownType):
536543
desert.schema_class(A)

0 commit comments

Comments
 (0)