Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tin/defaultdicts #588

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/cattrs/cols.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

from __future__ import annotations

from collections import defaultdict
from functools import partial
from sys import version_info
from typing import (
TYPE_CHECKING,
Any,
DefaultDict,
Iterable,
Literal,
NamedTuple,
Expand All @@ -16,7 +19,16 @@

from attrs import NOTHING, Attribute

from ._compat import ANIES, is_bare, is_frozenset, is_mapping, is_sequence, is_subclass
from ._compat import (
ANIES,
get_args,
get_origin,
is_bare,
is_frozenset,
is_mapping,
is_sequence,
is_subclass,
)
from ._compat import is_mutable_set as is_set
from .dispatch import StructureHook, UnstructureHook
from .errors import IterableValidationError, IterableValidationNote
Expand Down Expand Up @@ -289,3 +301,23 @@ def namedtuple_dict_unstructure_factory(
working_set.remove(cl)
if not working_set:
del already_generating.working_set


def is_defaultdict(type: Any) -> bool:
"""Is this type a defaultdict?

Bare defaultdicts (defaultdicts with no type arguments) are not supported
since there's no way to discover their _default_factory_.
"""
return is_subclass(get_origin(type), (defaultdict, DefaultDict))


def defaultdict_struct_factory(
type: type[defaultdict], converter: BaseConverter
) -> StructureHook:
"""A structure hook factory for defaultdicts.

The value type parameter will be used as the _default factory_.
"""
value_type = get_args(type)[1]
return mapping_structure_factory(type, converter, partial(defaultdict, value_type))
3 changes: 3 additions & 0 deletions src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
signature,
)
from .cols import (
defaultdict_struct_factory,
is_defaultdict,
is_namedtuple,
iterable_unstructure_factory,
list_structure_factory,
Expand Down Expand Up @@ -1174,6 +1176,7 @@ def __init__(
self.register_structure_hook_factory(is_annotated, self.gen_structure_annotated)
self.register_structure_hook_factory(is_mapping, self.gen_structure_mapping)
self.register_structure_hook_factory(is_counter, self.gen_structure_counter)
self.register_structure_hook_factory(is_defaultdict, defaultdict_struct_factory)
self.register_structure_hook_factory(is_typeddict, self.gen_structure_typeddict)
self.register_structure_hook_factory(
lambda t: get_newtype_base(t) is not None, self.get_structure_newtype
Expand Down
5 changes: 4 additions & 1 deletion src/cattrs/gen/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -919,11 +919,14 @@ def mapping_structure_factory(
structure_to: type = dict,
key_type=NOTHING,
val_type=NOTHING,
detailed_validation: bool = True,
detailed_validation: bool | Literal["from_converter"] = "from_converter",
) -> MappingStructureFn[T]:
"""Generate a specialized structure function for a mapping."""
fn_name = "structure_mapping"

if detailed_validation == "from_converter":
detailed_validation = converter.detailed_validation

globs: dict[str, type] = {"__cattr_mapping_cl": structure_to}

lines = []
Expand Down
24 changes: 24 additions & 0 deletions tests/test_defaultdicts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Tests for defaultdicts."""

from collections import defaultdict
from typing import DefaultDict

from cattrs import Converter


def test_typing_defaultdicts(genconverter: Converter):
"""`typing.DefaultDict` works."""
res = genconverter.structure({"a": 1}, DefaultDict[str, int])

assert isinstance(res, defaultdict)
assert res["a"] == 1
assert res["b"] == 0


def test_collection_defaultdicts(genconverter: Converter):
"""`collections.defaultdict` works."""
res = genconverter.structure({"a": 1}, defaultdict[str, int])

assert isinstance(res, defaultdict)
assert res["a"] == 1
assert res["b"] == 0
Loading