Guest User

Untitled

a guest
Jul 14th, 2020
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. class Node:
  2. def __init__(self, *args):
  3. self.args = args
  4. def __repr__(self):
  5. return str(self.args)
  6.  
  7. class List(Node):
  8. pass
  9.  
  10. class Union(Node):
  11. pass
  12.  
  13. class Dict(Node):
  14. pass
  15.  
  16. def iter_concrete_types(obj):
  17. if isinstance(obj, Union):
  18. for arg in obj.args:
  19. yield from iter_concrete_types(arg)
  20. elif isinstance(obj, List):
  21. for arg in obj.args:
  22. for t in iter_concrete_types(arg):
  23. yield f"List[{t}]"
  24. elif isinstance(obj, Dict):
  25. k,v = obj.args
  26. for tk in iter_concrete_types(k):
  27. for tv in iter_concrete_types(v):
  28. yield f"Dict[{tk}, {tv}]"
  29. elif isinstance(obj, type):
  30. yield obj.__name__
  31. else:
  32. raise Exception(f"Don't know how to concretize object of type {type(obj)}")
  33.  
  34. x = Union(List(Union(Dict(str, Union(int, List(int))), Dict(str, Union(Dict(str, Union(int, List(int))), List(int))))), Union(Dict(str, Union(int, List(int))), Dict(str, Union(Dict(str, Union(int, List(int))), List(int)))))
  35.  
  36. for t in iter_concrete_types(x):
  37. print(t)
  38.  
  39. """result:
  40. List[Dict[str, int]]
  41. List[Dict[str, List[int]]]
  42. List[Dict[str, Dict[str, int]]]
  43. List[Dict[str, Dict[str, List[int]]]]
  44. List[Dict[str, List[int]]]
  45. Dict[str, int]
  46. Dict[str, List[int]]
  47. Dict[str, Dict[str, int]]
  48. Dict[str, Dict[str, List[int]]]
  49. Dict[str, List[int]]
  50. """
Add Comment
Please, Sign In to add comment