Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import TypeVar, Callable, Any, Type, Dict
- T = TypeVar('T')
- def fold_union(conversions: Dict[Type, Callable[[Any], T]],
- value: Any,
- type_error_msg: Optional[str] = None,
- exhaustive_isinstance: bool = False, ) -> T:
- """Converts a `value` of a Union type into some other type `T`.
- The `conversions` dictionary maps valid sub-types for some `Union` type with functions that
- are able to convert from that specific type to a value of type `T`.
- The `value` parameter is a valid instance of the (implicitly defined) Union type.
- If `exhaustive_isinstance is True`, then each type -> converter mapping is checked to see if
- value input `value` is a valid instance of the key type. The first one that is encountered is
- is used: iteration order is according to `conversions`'s `items` method.
- Otherwise, the `type(value)` is used to index into the conversion mapping. If there is a
- converter for that exact type, it is used. This indexing behavior is the default.
- If no appropriate converter function is found, then this function raises a `TypeError`.
- If `type_error_msg is not None`, then it is used in the resulting `TypeError`, if `raise`d.
- Otherwise, the function will generate an error message that includes the input value's runtime
- type.
- Raises
- ------
- TypeError: If there is no appropriate union sub-type conversion function in `conversions`.
- """
- if exhaustive_isinstance:
- for u_impl_type, converter in conversions.items():
- if isinstance(value, u_impl_type):
- return converter(value)
- elif type(value) in conversions:
- return conversions[type(value)](value)
- raise TypeError(f"Could not resolve union for value of type {type(value)}: "
- f"sub-type conversion dictionary has no appropriate type mapping"
- if type_error_msg is None
- else type_error_msg)
Add Comment
Please, Sign In to add comment