-
-
Notifications
You must be signed in to change notification settings - Fork 118
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
immutable Mapping hooks #555
Comments
For anyone curious of my solution in the meantime: from typing import Type, Any, get_origin, TypeVar, Callable
import inspect
# Third Party Library
from cattrs import BaseConverter
from immutables import Map as frozenmap
T = TypeVar("T")
U = TypeVar("U")
def frozenmap_predicate(
typ: Type[Any],
) -> bool:
if inspect.isclass(typ):
return issubclass(typ, frozenmap)
elif is_generic_container_type(typ):
return get_origin(typ) is frozenmap
else:
return False
def frozenmap_unstructure_factory(typ: Type[frozenmap[T,U]]) -> Callable[[frozenmap[T,U]], dict[T,U]]:
return lambda d: dict(d)
def frozenmap_structure_factory(typ: Type[frozenmap[T,U]]) -> Callable[Any, Type[dict[T,U]], frozenmap[T,U]]:
return lambda d, t: frozenmap(d)
def register_frozenmap_hooks(converter: BaseConverter) -> None:
converter.register_structure_hook_factory(
frozenmap_predicate,
frozenmap_structure_factory,
)
converter.register_unstructure_hook_factory(
frozenmap_predicate,
frozenmap_unstructure_factory,
) |
I would think so via handling of ABCs. I'll check over this new documentation. I can't promise being able to write an MR anytime soon though. In general though perhaps there is a way to register standard hooks for anything satisfying subclass relations to |
I also use immutables so I'm interested in getting this working. I started a PR to play around with this over the next couple of days. |
Description
I am bringing in an immutable mapping data type (i.e.
immutables.Map
https://github.com/MagicStack/immutables) into my code.I think given that
issubclass(immutables.Map, Mapping == True
theis_mapping
predicate should work for it and there is really no special constructor for it.What I Did
My first attempt was to register these hooks:
Which works for a plain
frozenmap
annotation, but not for generic type specifiers. I can write the hook factory/predicate, but I don't see why theis_mapping
code should be specific to mutable mappings:cattrs/src/cattrs/_compat.py
Lines 407 to 419 in e2ce66b
The text was updated successfully, but these errors were encountered: