Created
February 2, 2022 01:38
-
-
Save mjambon/e4301e904f197e3b7e4bcf026a0be3b0 to your computer and use it in GitHub Desktop.
Python sum types for atdpy
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 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