Я хочу, чтобы новая функция использовала @singledispatch вместо проверки типа, но я не могу понять, как сохранить подсказку типа предыдущей функции:
< h2>Старая функция: использование проверки типов
Код: Выделить всё
import datetime
from typing import Union
MyDateTimeType = Union[int, str, datetime.datetime, datetime.date, None]
# How do I retain this functionality with @singledispatch?
# ⬇️⬇️⬇️⬇️⬇️⬇️⬇️
def to_unix_ts(date: MyDateTimeType = None) -> Union[int, None]:
"""Convert various date formats to Unix timestamp..."""
if type(date) is int or date is None:
return date
if type(date) is str:
# Handle string argument...
elif type(date) is datetime.datetime:
# Handle datetime argument...
elif type(date) is datetime.date:
# Handle date argument...
Код: Выделить всё
import datetime
from functools import singledispatch
from typing import Union
@singledispatch
def to_unix_ts(date) -> Union[int, None]:
"""Handle generic case (probably string type)..."""
@to_unix_ts.register
def _(date: int) -> int:
return date
@to_unix_ts.register
def _(date: None) -> None:
return date
@to_unix_ts.register
def _(date: datetime.datetime) -> int:
return int(date.replace(microsecond=0).timestamp())
# etc...
Код: Выделить всё
supported_types = [type for type in to_unix_ts.registry.keys()]
MyDateTimeType = Union(supported_types) # Example, doesn't work
Как можно Я добавляю подсказки типа стиля Union[...] в функцию @singledispatch с возможностью расширения?
Подробнее здесь: https://stackoverflow.com/questions/617 ... tensible-w