-
-
Notifications
You must be signed in to change notification settings - Fork 133
Closed
Description
- cattrs version: 1.4.0
- Python version: 3.9.2
- Operating System: Linux
Description
It looks like using auto_attribs=True and type annotations can break the code which otherwise invokes a converter specified via attr.ib(converter=<something>).
What I Did
import attr
import cattr
from ipaddress import IPv4Address
## Works
@attr.s
class Works:
ip = attr.ib(converter=IPv4Address)
print(cattr.structure({"ip": "10.0.0.0"}, Works))
## Does not work
@attr.s(auto_attribs=True)
class DoesNotWork:
ip: IPv4Address = attr.ib(converter=IPv4Address)
try:
print(cattr.structure({"ip": "10.0.0.0"}, DoesNotWork))
except Exception as e:
print(e)
try:
converter = cattr.GenConverter()
print(converter.structure({"ip": "10.0.0.0"}, DoesNotWork))
except Exception as e:
print(e)Traceback:
Traceback (most recent call last):
File "/home/nate/workspace/test.py", line 17, in <module>
print(cattr.structure({"a": "10.0.0.0"}, A))
File "/home/nate/workspace/.venv/lib/python3.9/site-packages/cattr/converters.py", line 205, in structure
return self._structure_func.dispatch(cl)(obj, cl)
File "/home/nate/workspace/.venv/lib/python3.9/site-packages/cattr/converters.py", line 342, in structure_attrs_fromdict
dispatch(type_)(val, type_) if type_ is not None else val
File "/home/nate/workspace/.venv/lib/python3.9/site-packages/cattr/converters.py", line 286, in _structure_default
raise ValueError(msg)
ValueError: Unsupported type: <class 'ipaddress.IPv4Address'>. Register a structure hook for it.
Workaround
Manually register converters instead of using attr.ib(converter=)
converter = cattr.GenConverter()
converter.register_structure_hook(IPv4Address, lambda val, _: IPv4Address(val))Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels