Closed salotz closed 4 months ago
Hello!
The short answer: you should use register_structure_hook
for primitive types like int
, str
, bytes
, floats
.
The long answer: cattrs has two mechanisms for looking up hooks for types. The first one is based on functools.singledispatch
, it's the older of the two, and it's easy and simple. It doesn't support factories, so it's appropriate for simple types.
The second one is based on predicates. It's the more complex and more powerful one.
cattrs has to check one, and then the other. Because of historical reasons, for backwards compatibility and also because it I think it makes sense, the singledispatch
mechanism is used first and then the predicate mechanism.
You're trying to customize int
behavior using the predicate mechanism, but the default hook for int
uses singledispatch, so that triggers first. So in order to successfully override these hooks, you can use register_structure_hook
instead.
Hope this helps!
Description
I am trying to register custom converters for built in types and I found this doesn't always work as expected.
I have a better workaround than using factories like this, but I wanted to understand why this doesn't work as expected.
What I Did