Skip to content

immutable Mapping hooks #555

@salotz

Description

@salotz
  • cattrs version: 23.2.3
  • Python version: 3.11
  • Operating System: Linux

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 the is_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:

from immutables import Map as frozenmap
...
converter.register_structure_hook(frozenmap, lambda d, t: frozenmap(d))
converter.register_unstructure_hook(frozenmap, lambda d: dict(d))

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 the is_mapping code should be specific to mutable mappings:

def is_mapping(type):
return (
type in (dict, Dict, TypingMapping, TypingMutableMapping, AbcMutableMapping)
or (
type.__class__ is _GenericAlias
and is_subclass(type.__origin__, TypingMapping)
)
or (
getattr(type, "__origin__", None)
in (dict, AbcMutableMapping, AbcMapping)
)
or is_subclass(type, dict)
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions