mverleg / pyjson_tricks

Extra features for Python's JSON: comments, order, numpy, pandas, datetimes, and many more! Simple but customizable.
Other
152 stars 23 forks source link

attrs class instances that use __weakref__ cannot be decoded #82

Closed dominicdoty closed 1 year ago

dominicdoty commented 1 year ago

I have a class that is defined with attrs (@attrs.define), which defaults to having a __weakref__ entry in __slots__.

It looks like this causes decoding to fail since the __weakref__ attribute of the new instance already exists is not writeable in decoding, producing this error:
AttributeError: attribute '__weakref__' of 'MyClass' objects is not writable

It seems like the load method would need to detect that the class already has __weakref__ defined and not attempt to re-define it.

Not sure if this is a corner case for json_tricks that won't be fixed, but I figured I'd point it out! Thanks!

dominicdoty commented 1 year ago

Minimal reproducible example:

# attrs                  22.1.0
# json-tricks            3.15.5
# Python 3.7.9

import attrs
import json_tricks

@attrs.define(kw_only=True)
class MyClass:
    value: float = attrs.field(converter=float, default=0.0)
    more_value: float = attrs.field(converter=float, default=0.0)

if __name__ == "__main__":
    p = MyClass(value=1.0, more_value=0.99)
    p_str = json_tricks.dumps(p)
    decoded = json_tricks.loads(p_str)
mverleg commented 1 year ago

Thanks @dominicdoty I wasn't aware of this issue, it should be supported!

mverleg commented 1 year ago

I release 3.15.6 let me know if you have any issues with it