Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from typing import NamedTuple
import json
class NamedTupleJSONEncoder(json.JSONEncoder):
def encode(self, o):
print(f"Encoding {type(o)}")
return super().encode(o)
def iterencode(self, o, _one_shot=False):
print(f"Iterencoding {type(o)}")
if isinstance(o, tuple):
try:
return super().iterencode(o._asdict(), _one_shot=_one_shot)
except AttributeError:
return super().iterencode(o, _one_shot=_one_shot)
return super().iterencode(o, _one_shot=_one_shot)
def default(self, o):
print(f"Defaulted {type(o)}")
if isinstance(o, tuple):
try:
return o._asdict()
except AttributeError:
return super().default(o)
return super().default(o)
class CoolStuff(NamedTuple):
cool: str
stuff: int
class NeatGoo(NamedTuple):
neat: CoolStuff
goo: CoolStuff
things = CoolStuff("hello", 3)
other_things = CoolStuff("goodbye", 4)
neato = NeatGoo(things, other_things)
print(json.dumps(neato, cls=NamedTupleJSONEncoder))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment