Guest User

Untitled

a guest
May 23rd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. from typing import TypeVar, Callable, Any, Type, Dict
  2.  
  3. T = TypeVar('T')
  4.  
  5. def fold_union(conversions: Dict[Type, Callable[[Any], T]],
  6. value: Any,
  7. type_error_msg: Optional[str] = None,
  8. exhaustive_isinstance: bool = False, ) -> T:
  9. """Converts a `value` of a Union type into some other type `T`.
  10.  
  11. The `conversions` dictionary maps valid sub-types for some `Union` type with functions that
  12. are able to convert from that specific type to a value of type `T`.
  13.  
  14. The `value` parameter is a valid instance of the (implicitly defined) Union type.
  15.  
  16. If `exhaustive_isinstance is True`, then each type -> converter mapping is checked to see if
  17. value input `value` is a valid instance of the key type. The first one that is encountered is
  18. is used: iteration order is according to `conversions`'s `items` method.
  19. Otherwise, the `type(value)` is used to index into the conversion mapping. If there is a
  20. converter for that exact type, it is used. This indexing behavior is the default.
  21.  
  22. If no appropriate converter function is found, then this function raises a `TypeError`.
  23.  
  24. If `type_error_msg is not None`, then it is used in the resulting `TypeError`, if `raise`d.
  25. Otherwise, the function will generate an error message that includes the input value's runtime
  26. type.
  27.  
  28. Raises
  29. ------
  30. TypeError: If there is no appropriate union sub-type conversion function in `conversions`.
  31. """
  32. if exhaustive_isinstance:
  33. for u_impl_type, converter in conversions.items():
  34. if isinstance(value, u_impl_type):
  35. return converter(value)
  36.  
  37. elif type(value) in conversions:
  38. return conversions[type(value)](value)
  39.  
  40. raise TypeError(f"Could not resolve union for value of type {type(value)}: "
  41. f"sub-type conversion dictionary has no appropriate type mapping"
  42. if type_error_msg is None
  43. else type_error_msg)
Add Comment
Please, Sign In to add comment