Created
May 13, 2019 16:55
-
-
Save MattOates/415ba64ca35d1f861eaa762b41104329 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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