如何从打字联合中获取类型列表?

问题描述

我正在编写一个将 function 对象作为属性的类,并自动构建用于执行给定功能的UI。

我需要知道 function 的每个参数应为哪种类型,以便编写匹配的输入小部件(例如:布尔参数的复选框)。我设法使用self.func.__annotations__获得了预期的类型。

问题是,有些函数为某个参数获取多种数据类型-并用typing.Union[]进行注释。我希望通过允许用户选择要为此特定参数输入的数据类型来在UI中处理这些情况,但是我无法从typing.Union[]获取类型列表。

class FunctionUI:
    def __init__(self,func):
        self.func = func
        self.params_to_dtypes = {k: v.__name__ for k,v in self.func.__annotations__.items()}

def foo(a: str,b: list):
    print(a)
    print(b)

fui = FunctionUI(foo)
print(fui.params_to_dtypes)

现在我的输出是:

{'a': 'str','b': 'list'}

我正在寻找的理想解决方案应如下所示:

from typing import Union

def foo(a: str,b: Union[list,str]):
    print(a)
    print(b)

fui = FunctionUI(foo)
print(fui.params_to_dtypes)

输出:

{'a': 'str','b': ['list','str']}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...