I am using JSON to send data from Python to R (note: I'm much more familiar with R than Python). For primitives, the json
module works great. For many other Python objects (e.g. numpy
arrays) you have to define a custom encoder, like in this stack overflow answer. However, that requires you to pass the encoder as an argument to json.dumps
, which doesn't work that well for my case.
I know there are other packages like json_tricks
that have much more advanced capabilities for JSON serialization, but since I don't have control over what Python distribution a user has I don't want to rely on any non-default modules for serializing objects to JSON.
I'm wondering if there is a way to use decorators to define additional ways for serializing JSON objects. Ideally, I'm looking for a way that would allow users to overload some standard function contextlib
standard_wrapper
that I provide to add new methods for their own classes (or types from modules that they load) without requiring them to modify standard_wrapper
. Some psuedocode below:
import json
def standard_wrapper(o):
return o
obj = [44,64,13,4,79,2,454,89,0]
json.dumps(obj)
json.dumps(standard_wrapper(obj))
import numpy as np
objnp = np.sort(obj)
json.dumps(objnp) # FAILS
@some_decorator_to_overload_standard_wrapper
# some code
json.dumps(standard_wrapper(objnp)) # HOPEFULLY WORKS
This is essentially function overloading by type---I've seen examples for overloading by arguments in Python, but I don't see how to do it by type.
EDIT I was mixing up decorators with contextlib
(which I had only ever seen used a decorator).