python-attrs / cattrs

Composable custom class converters for attrs, dataclasses and friends.
https://catt.rs
MIT License
781 stars 108 forks source link

Structure failed with `typing_extensions.Any` #488

Closed WEGFan closed 5 months ago

WEGFan commented 6 months ago

Description

Structure failed and raises cattrs.errors.StructureHandlerNotFoundError: Unsupported type: typing_extensions.Any. Register a structure hook for it.. It succeeds if I use typing.Any.

typing_extension version is 4.9.0

What I Did

>>> import cattrs
>>> import typing as t
>>> import typing_extensions as te
>>> cattrs.structure(1, te.Any)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.10/site-packages/cattrs/converters.py", line 332, in structure
    return self._structure_func.dispatch(cl)(obj, cl)
  File "/usr/local/lib/python3.10/site-packages/cattrs/fns.py", line 17, in raise_error
    raise StructureHandlerNotFoundError(msg, type_=cl)
cattrs.errors.StructureHandlerNotFoundError: Unsupported type: typing_extensions.Any. Register a structure hook for it.
>>> cattrs.structure(1, t.Any)
1
>>> cattrs.structure([1], list[te.Any])
  + Exception Group Traceback (most recent call last):
  |   File "<stdin>", line 1, in <module>
  |   File "/usr/local/lib/python3.10/site-packages/cattrs/converters.py", line 332, in structure
  |     return self._structure_func.dispatch(cl)(obj, cl)
  |   File "/usr/local/lib/python3.10/site-packages/cattrs/converters.py", line 531, in _structure_list
  |     raise IterableValidationError(
  | cattrs.errors.IterableValidationError: While structuring list[typing_extensions.Any] (1 sub-exception)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "/usr/local/lib/python3.10/site-packages/cattrs/converters.py", line 521, in _structure_list
    |     res.append(handler(e, elem_type))
    |   File "/usr/local/lib/python3.10/site-packages/cattrs/fns.py", line 17, in raise_error
    |     raise StructureHandlerNotFoundError(msg, type_=cl)
    | cattrs.errors.StructureHandlerNotFoundError: Unsupported type: typing_extensions.Any. Register a structure hook for it.
    | Structuring list[typing_extensions.Any] @ index 0
    +------------------------------------
>>> cattrs.structure([1], list[t.Any])
[1]
Tinche commented 6 months ago

Ugh, why does typing_extensions have their own Any type now?

In the mean time, you can do this to enable support:

from typing_extensions import Any

from cattrs import Converter

c = Converter()

c.register_structure_hook_func(lambda t: t is Any, lambda v, _: v)
WEGFan commented 6 months ago

Seems that it isn't an issue on Python >= 3.11

https://github.com/python/typing_extensions/blob/f84880d60b1d5f7b4ceaab563e7eeb6021f4ca13/src/typing_extensions.py#L215-L242

Tinche commented 6 months ago

I guess because it's possible to subclass Any now. I can add support for it in the next version.