gemini-code-assist[bot] commented on code in PR #643:
URL: https://github.com/apache/tvm-ffi/pull/643#discussion_r3461042422
##########
python/tvm_ffi/cython/string.pxi:
##########
@@ -57,6 +57,9 @@ class String(str, PyNativeObject):
val._tvm_ffi_cached_object = None
return val
+ def __reduce_ex__(self, protocol):
+ return (type(self), (str(self),))
Review Comment:

If `String` is subclassed, any custom attributes stored in the instance's
`__dict__` will be silently lost during pickling because the returned 2-tuple
does not include the state dictionary.
To ensure robustness for subclasses, we can copy `self.__dict__` (if it
exists), remove `_tvm_ffi_cached_object`, and return it as the third element
(the state) of the reduction tuple.
```
def __reduce_ex__(self, protocol):
state = self.__dict__.copy() if hasattr(self, "__dict__") else {}
state.pop("_tvm_ffi_cached_object", None)
return (type(self), (str(self),), state or None)
```
##########
python/tvm_ffi/cython/string.pxi:
##########
@@ -80,6 +83,9 @@ class Bytes(bytes, PyNativeObject):
val._tvm_ffi_cached_object = None
return val
+ def __reduce_ex__(self, protocol):
+ return (type(self), (bytes(self),))
Review Comment:

Since `Bytes` does not define `__slots__` (due to Python limitations on
`bytes` subclasses), it always has an instance `__dict__`. The current
implementation of `__reduce_ex__` returns a 2-tuple, which completely discards
the `__dict__` during pickling. This means any custom attributes attached to a
`Bytes` instance (or its subclasses) will be silently lost upon
pickling/unpickling.
To preserve other custom attributes while still safely discarding
`_tvm_ffi_cached_object`, we can copy `self.__dict__`, remove
`_tvm_ffi_cached_object`, and return it as the third element (the state) of the
reduction tuple.
```
def __reduce_ex__(self, protocol):
state = self.__dict__.copy() if hasattr(self, "__dict__") else {}
state.pop("_tvm_ffi_cached_object", None)
return (type(self), (bytes(self),), state or None)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]