Skip to content

Instantly share code, notes, and snippets.

@MattOates
Created May 13, 2019 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattOates/415ba64ca35d1f861eaa762b41104329 to your computer and use it in GitHub Desktop.
Save MattOates/415ba64ca35d1f861eaa762b41104329 to your computer and use it in GitHub Desktop.
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