Python 键入提示和@singledispatch:如何以可扩展的方式包括'Union[…]'?

Python 键入提示和@singledispatch:如何以可扩展的方式包括'Union[…]'?,python,type-hinting,single-dispatch,Python,Type Hinting,Single Dispatch,我正在重构一个函数,该函数将多种日期格式(例如ISO 8601字符串、datetime.date、datetime.datetime)转换为Unix时间戳 我希望新函数使用@singledispatch而不是类型检查,但我不知道如何保留以前函数的类型提示: 旧功能:使用类型检查 导入日期时间 从键入导入联合 MyDateTimeType=Union[int,str,datetime.datetime,datetime.date,None] #如何使用@singledispatch保留此功能? #

我正在重构一个函数,该函数将多种日期格式(例如ISO 8601字符串、
datetime.date
datetime.datetime
)转换为Unix时间戳

我希望新函数使用
@singledispatch
而不是类型检查,但我不知道如何保留以前函数的类型提示:

旧功能:使用类型检查
导入日期时间
从键入导入联合
MyDateTimeType=Union[int,str,datetime.datetime,datetime.date,None]
#如何使用@singledispatch保留此功能?
#                    ⬇️⬇️⬇️⬇️⬇️⬇️⬇️
def to_unix_ts(日期:MyDateTimeType=None)->Union[int,None]:
“”“将各种日期格式转换为Unix时间戳…”“”
如果类型(日期)为int或日期为None:
返回日期
如果类型(日期)为str:
#处理字符串参数。。。
elif类型(日期)为datetime.datetime:
#处理日期时间参数。。。
elif类型(日期)为datetime.date:
#处理日期参数。。。
新功能:使用
@singledispatch
导入日期时间
从functools导入singledispatch
从键入导入联合
@单发
def to_unix_ts(日期)->Union[int,None]:
“”“处理泛型大小写(可能是字符串类型)
@到unix注册
定义(日期:int)->int:
返回日期
@到unix注册
定义(日期:无)->无:
返回日期
@到unix注册
定义(日期:datetime.datetime)->int:
返回int(date.replace(微秒=0).timestamp())
#等等。。。
我探讨了如何构建支持的类型,如下所示:

supported_types = [type for type in to_unix_ts.registry.keys()]
MyDateTimeType = Union(supported_types)  # Example, doesn't work
…因此它可以通过将来的@singledispatch注册进行扩展,但我无法让它工作


如何以可扩展的方式在
@singledispatch
函数中添加
Union[…]
样式类型提示?

如果您真想让类型提示物有所值,就必须手动添加。用运行时动态生成的信息注释某些东西有什么用?@juanpa.arrivillaga My IDE的内省经常在我键入时捕捉到键入错误;)正如您所期望的那样,它可以在类似的运行时场景(如类继承)中智能地组合类型。如果我没有忽略任何东西,那么我的问题可能不是语言问题,而是IDE实现?