convert_to#
- convert_to(obj, to_type: str | list[str], as_scitype: str | list[str] = None, store=None, store_behaviour: str = None, return_to_mtype: bool = False)[source]#
将对象转换为不同的机器表示,受 scitype 约束。
- 参数:
- obj 要转换的对象 - 任何类型,应符合 as_scitype 的 mtype 规范
- to_type str - 要将“obj”转换为的 mtype,一个有效的 mtype 字符串
或 str 列表,这指定了可接受的转换类型;如果是列表,将转换为与 obj 具有相同 scitype 的第一个 mtype;有效的 mtype 字符串及其解释位于 datatypes.MTYPE_REGISTER 中
- as_scitype str,可选 - 对象“obj”被视为的 scitype 名称
预先指定 scitype 可以减少类型推断中进行的检查次数;有效的 scitype 字符串及其解释位于 datatypes.SCITYPE_REGISTER 中;默认值 = 从 obj 的 mtype 推断,后者再在内部推断
- store 有损转换的存储引用,默认值 = None (不存储)
如果 store 不为 None 且 store_behaviour=”reset” 或 “update”,则通过副作用更新
- store_behaviour str,可选,为 None (默认)、“reset”、“freeze”、“update”之一
“reset” - store 被清空,然后从转换中更新 “freeze” - store 是只读的,转换可以读取/使用但不能更改 “update” - store 从转换中更新并保留先前的内容 None - 自动:如果 store 为空且不为 None,则为“update”;否则为“freeze”
- return_to_mtype: bool,可选 (默认值=False)
如果为 True,也返回转换后 mtype 的 str
- 返回值:
- converted_obj to_type - 对象 obj,或按如下方式转换为目标 mtype 的 obj:
- 情况 1:obj 的 mtype 等于 to_type,或 to_type 的列表元素
不发生转换,converted_obj = obj
- 情况 2:to_type 是 str,且不等于 obj 的 mtype
converted_obj 是转换为 to_type 的 obj
- 情况 3:to_type 是 str 列表,且 obj 的 mtype 不在该列表中
- converted_obj 将转换为 to_type 中第一个
与 obj 具有相同 scitype 的 mtype
情况 4:如果 obj 为 None,则 converted_obj 也为 None
- to_type str,仅当
return_to_mtype=True
时返回 converted_obj 的 mtype - 如果
to_type
是列表,则很有用
- 引发:
- 如果输入的“obj”的机器类型无法识别,则引发 TypeError
- 如果 to_type 不包含与 obj 的 mtype 兼容的 mtype,则引发 TypeError
- 如果将要进行的转换未实现,则引发 KeyError
- 如果输入与规范不符,则引发 TypeError 或 ValueError