python 中获取 uniontype 的子成员
uniontype 可以表示类型的联合,在 python 中,可以利用 uniontype 来指定一个参数可以接收多种类型。但是,如何获取 uniontype 的子成员呢?该如何判断一个指定类型是否在 uniontype 中?
获取 uniontype 的子成员
from typing import union from inspect import signature def check_func_args_hints(func): typed_signature = signature(func).parameters.items() # 获取函数的参数 for _, parameter in typed_signature: # 遍历所有参数 if isinstance(parameter.annotation, union): # 检查参数类型是否为 uniontype return typing.get_args(parameter.annotation) # 返回 uniontype 的子成员
def get_score(name: str | none = none) -> float | none: # 定义一个包含 uniontype 的函数 pass result = check_func_args_hints(get_score) print(result) # 输出:('str', nonetype)
判断指定类型是否在 uniontype 中
立即学习“Python免费学习笔记(深入)”;
is_str_in_union = isinstance('', parameter.annotation) # true 如果 parameter.annotation 包含 str
if type(parameter.annotation) != Union or str in parameter.annotation: is_str_in_union = True
以上方法可以帮助你获取 uniontype 的子成员和判断指定类型是否在 uniontype 中,满足你的需求。
以上就是如何在 Python 中获取 UnionType 的子成员和判断指定类型是否在 UnionType 中?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号