def make_optional( name: Text, elem_type: OptionalProto.DataType, value: Optional[Any], ) -> OptionalProto: ''' Make an Optional with specified value arguments. ''' optional = OptionalProto() optional.name = name optional.elem_type = elem_type if elem_type != 0: values_field = mapping.OPTIONAL_ELEMENT_TYPE_TO_FIELD[elem_type] getattr(optional, values_field).CopyFrom(value) return optional
def from_optional(opt: Optional[Any], name: Optional[Text] = None, dtype: Optional[int] = None) -> OptionalProto: """Converts an optional value into a Optional def. Inputs: opt: a Python optional name: (optional) the name of the optional. dtype: (optional) type of element in the input, used for specifying optional values when converting empty none. dtype must be a valid OptionalProto.DataType value Returns: optional: the converted optional def. """ # TODO: create a map and replace conditional branches optional = OptionalProto() if name: optional.name = name if dtype: # dtype must be a valid OptionalProto.DataType valid_dtypes = [v for v in OptionalProto.DataType.values()] assert dtype in valid_dtypes elem_type = dtype elif isinstance(opt, dict): elem_type = OptionalProto.MAP elif isinstance(opt, list): elem_type = OptionalProto.SEQUENCE elif opt is None: elem_type = OptionalProto.UNDEFINED else: elem_type = OptionalProto.TENSOR optional.elem_type = elem_type if opt is not None: if elem_type == OptionalProto.TENSOR: optional.tensor_value.CopyFrom(from_array(opt)) elif elem_type == OptionalProto.SEQUENCE: optional.sequence_value.CopyFrom(from_list(opt)) elif elem_type == OptionalProto.MAP: optional.map_value.CopyFrom(from_dict(opt)) else: raise TypeError("The element type in the input is not a tensor, " "sequence, or map and is not supported.") return optional