Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encode ignores __getstate__ returning empty dict #454

Open
sitnarf opened this issue Aug 4, 2023 · 2 comments
Open

encode ignores __getstate__ returning empty dict #454

sitnarf opened this issue Aug 4, 2023 · 2 comments

Comments

@sitnarf
Copy link

sitnarf commented Aug 4, 2023

I have a custom __getstate__ which excludes attributes that are not seriazable. However if there are no other attributes and __getstate__ therefore returns an empty dict, jsonpickle.encode ignores __getstate__, resulting in an error.

The problem is here (line 627):

if has_own_getstate:
try:
state = obj.__getstate__()
except TypeError:
# Has getstate but it cannot be called, e.g. file descriptors
# in Python3
self._pickle_warning(obj)
return None
else:
if state:
return self._getstate(state, data)

Just for clarity, this is my code:

class Serializable:
    def __getstate__(self):
        state = copy(self.__dict__)
        exclude = getattr(self, "__exclude__", [])

        for name in exclude:
            state.pop(name, None)
 
       return state
class ServerConnection(Serializable):
    client_ws: WebSocketClientProtocol
    websocket_server: WebSocketClientProtocol

    __exclude__ = ["websocket_server", "client_ws"]

   ...
@sitnarf sitnarf changed the title encode ignores __getstate__ when returning empty dict encode ignores __getstate__ returning empty dict Aug 8, 2023
@Theelx
Copy link
Contributor

Theelx commented Aug 8, 2023

Thanks for reporting this! I'm unsure how to properly handle this while maintaining backwards-compatibility though, since this seems like behavior that some people would rely on. I know that the project for which I use jsonpickle actually does rely on this behavior. Would a feature flag be an acceptable solution for this use case?

@sitnarf
Copy link
Author

sitnarf commented Sep 1, 2023

A feature flag sounds good to me.

@Theelx Theelx added this to the 3.1.0 milestone Mar 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants