解包Optional值的功能函数
项目描述
unopt:解包Optional[T]
的功能函数
概述
unopt提供了一些功能函数来“解包”Optional[T]
(或T | None
)对象:移除Optional
类型提示并获取底层对象。
unopt函数受到Rust的Option<T>
功能启发,但其行为调整为符合Python的惯例。例如,unwrap()
会引发异常而不是中断。
安装
pip install unopt
示例
from unopt import *
foo: Optional[int] = 123
bar: Optional[int] = None
# unwrap() returns the given object if it is not None.
assert unwrap(foo) == 123
unwrap(bar) # Raises UnwrapError
# unwrap_or() returns the default value if the given object is None.
assert unwrap_or(foo, 456) == 123
assert unwrap_or(bar, 456) == 456
# unwrap_or_else() returns the default value obtained by invoking the given function.
assert unwrap_or_else(foo, lambda: 456) == 123
assert unwrap_or_else(bar, lambda: 456) == 456
# unwrap_unchecked() just casts the given object without value checking.
assert unwrap_unchecked(foo) == 123
assert unwrap_unchecked(bar) is None # Unsafe
项目详情
下载文件
下载适用于您的平台的文件。如果不确定要选择哪个,请了解有关安装包的更多信息。
源分发
unopt-0.2.0.tar.gz (3.8 kB 查看哈希值)
构建分发
unopt-0.2.0-py3-none-any.whl (3.8 kB 查看哈希值)