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

Newtypes #255

Merged
merged 7 commits into from
Apr 15, 2022
Merged
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
2 changes: 2 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ History
* ``cattrs.Converter`` has been renamed to ``cattrs.BaseConverter``, and ``cattrs.GenConverter`` to ``cattrs.Converter``.
The ``GenConverter`` symbol is still available for backwards compatibility, but is deprecated.
If you were depending on functionality specific to the old ``Converter``, change your import to ``from cattrs import BaseConverter``.
* ``cattrs.Converter`` (what was previously the ``GenConverter``) now supports NewTypes.
(`#255 <https://github.com/python-attrs/cattrs/pull/255>`_, `#94 <https://github.com/python-attrs/cattrs/issues/94>`_)

22.1.0 (2022-04-03)
-------------------
Expand Down
44 changes: 22 additions & 22 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions src/cattrs/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import MutableMapping as TypingMutableMapping
from typing import MutableSequence as TypingMutableSequence
from typing import MutableSet as TypingMutableSet
from typing import NewType, Optional
from typing import Sequence as TypingSequence
from typing import Set as TypingSet
from typing import Tuple, get_type_hints
Expand Down Expand Up @@ -133,6 +134,16 @@ def is_union_type(obj):
obj is Union or isinstance(obj, _GenericAlias) and obj.__origin__ is Union
)

def get_newtype_base(typ: Any) -> Optional[type]:
supertype = getattr(typ, "__supertype__", None)
if (
supertype is not None
and getattr(typ, "__qualname__", "") == "NewType.<locals>.new_type"
and typ.__module__ in ("typing", "typing_extensions")
):
return supertype
return None

def is_sequence(type: Any) -> bool:
return type in (List, list, Tuple, tuple) or (
type.__class__ is _GenericAlias
Expand Down Expand Up @@ -258,6 +269,11 @@ def is_union_type(obj):
or isinstance(obj, UnionType)
)

def get_newtype_base(typ: Any) -> Optional[type]:
if typ is NewType or isinstance(typ, NewType):
return typ.__supertype__
return None

else:

def is_union_type(obj):
Expand All @@ -267,6 +283,16 @@ def is_union_type(obj):
and obj.__origin__ is Union
)

def get_newtype_base(typ: Any) -> Optional[type]:
supertype = getattr(typ, "__supertype__", None)
if (
supertype is not None
and getattr(typ, "__qualname__", "") == "NewType.<locals>.new_type"
and typ.__module__ in ("typing", "typing_extensions")
):
return supertype
return None

def is_sequence(type: Any) -> bool:
origin = getattr(type, "__origin__", None)
return (
Expand Down
17 changes: 17 additions & 0 deletions src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
Sequence,
Set,
fields,
get_newtype_base,
get_origin,
has,
has_with_generic,
Expand Down Expand Up @@ -150,6 +151,7 @@ def __init__(
[
(lambda cl: cl is Any or cl is Optional or cl is None, lambda v, _: v),
(is_generic_attrs, self._gen_structure_generic, True),
(lambda t: get_newtype_base(t) is not None, self._structure_newtype),
(is_literal, self._structure_simple_literal),
(is_literal_containing_enums, self._structure_enum_literal),
(is_sequence, self._structure_list),
Expand Down Expand Up @@ -393,6 +395,10 @@ def _structure_enum_literal(val, type):
except KeyError:
raise Exception(f"{val} not in literal {type}") from None

def _structure_newtype(self, val, type):
base = get_newtype_base(type)
return self._structure_func.dispatch(base)(val, base)

# Attrs classes.

def structure_attrs_fromtuple(self, obj: Tuple[Any, ...], cl: Type[T]) -> T:
Expand Down Expand Up @@ -715,9 +721,20 @@ def __init__(
is_frozenset,
lambda cl: self.gen_unstructure_iterable(cl, unstructure_to=frozenset),
)
self.register_unstructure_hook_factory(
lambda t: get_newtype_base(t) is not None,
lambda t: self._unstructure_func.dispatch(get_newtype_base(t)),
)
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(
lambda t: get_newtype_base(t) is not None, self.get_structure_newtype
)

def get_structure_newtype(self, type: Type[T]) -> Callable[[Any, Any], T]:
base = get_newtype_base(type)
return self._structure_func.dispatch(base)

def gen_unstructure_annotated(self, type):
origin = type.__origin__
Expand Down
Loading