Skip to content

Instantly share code, notes, and snippets.

@mjambon
Created February 2, 2022 01:38
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 mjambon/e4301e904f197e3b7e4bcf026a0be3b0 to your computer and use it in GitHub Desktop.
Save mjambon/e4301e904f197e3b7e4bcf026a0be3b0 to your computer and use it in GitHub Desktop.
Python sum types for atdpy
from typing import List
import json
# type t = A | B of int
class T:
pass
class T_A(T):
def __repr__(self):
return 'A'
def to_json(self):
return 'A'
def to_json_string(self) -> str:
return json.dumps(self.to_json())
class T_B(T):
def __init__(self, value):
self._value: int = value
def __repr__(self):
return f"B({self._value})"
def value(self):
return self._value
def to_json(self):
return ['B', self._value]
def to_json_string(self) -> str:
return json.dumps(self.to_json())
print("Testing __repr__")
things: List[T] = [T_A(), T_B(77)]
print(things)
print("Testing to_json_string")
print(T_A().to_json_string())
print(T_B(22).to_json_string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment