2

I was wondering if there's such a thing as the __sleep() magic function (from PHP) implemented in Python.

I'm having an issue with a class, which Python says it's not JSON serializable, and I want to return a simple dictionary from a magic method inside the class, so that one of my libs can successfully call json.dumps on it. (I have no control of the line of code that does the serialization, as I said, it's done inside a library)

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Eduard Luca
  • 6,514
  • 16
  • 85
  • 137
  • Can you monkey patch it or influence the `obj` that gets passed to `json.dumps`? – Simeon Visser Sep 05 '14 at 09:51
  • @SimeonVisser Yeah, it's a custom object I created. – Eduard Luca Sep 05 '14 at 09:51
  • Will the library need to interact with your object or does it just `json.dumps` it? In the latter case, you could always convert your object into something dump-able just before you give it to the library. – Duncan Jones Sep 05 '14 at 09:57
  • Take a look here: http://stackoverflow.com/questions/3768895/python-how-to-make-a-class-json-serializable the accepted answer suggests using JSONEncoder. Maybe it will help you encode your object. You can have this JSONEncoder subclass as a member of your custom class – Maciek Sep 05 '14 at 10:04
  • @Duncan that's what I ended up doing. Made a `to_dict` method on my object, and passing that as the param to the method that does the encoding, and on the other side, I'm populating a new instance of the class from the dictionary. If you'd kindly post the comment as an answer, I'd be glad to accept it. – Eduard Luca Sep 05 '14 at 11:08

1 Answers1

2

Unfortunately this is tricky if you have no control over the call to json.dumps(). If you did, there are a number of ways this could be solved (most notably by implementing a default function in a subclassed JSON encoder).

In your particular case, you are best to convert your object to a serializable form prior to passing it to the library. That way, when json.dumps() is called, your input can be serialized without error. This assumes that the library doesn't need to interact with your object and simply dumps it.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254