Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Last active December 24, 2015 02:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treyhunner/6734816 to your computer and use it in GitHub Desktop.
Save treyhunner/6734816 to your computer and use it in GitHub Desktop.
Using single-dispatch generic functions (PEP 443) to implement an extensible JSON encoder To use with Python 2.6 to 3.3, install singledispatch from PyPI.
from decimal import Decimal
from json_singledispatch import encode
@encode.register(set)
def encode_set(obj):
return encode(list(obj))
@encode.register(Decimal)
def encode_decimal(obj):
return encode(str(obj))
print encode({'key': "value"})
print encode({5, 6})
print encode(Decimal("5.6"))
import json
from singledispatch import singledispatch
class _CustomEncoder(json.JSONEncoder):
def default(self, obj):
for type_, handler in encode.registry.items():
if isinstance(obj, type_) and type_ is not object:
return handler(obj)
return super(_CustomEncoder, self).default(obj)
@singledispatch
def encode(obj, **kwargs):
return json.dumps(obj, cls=_CustomEncoder, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment