类型提示和@singledispatch:如何以可扩展的方式包含 `Union[...]`?

2023-12-27

我正在重构一个转换各种日期格式的函数(即 ISO 8601 字符串,datetime.date, datetime.datetime等)转换为 Unix 时间戳。

我想要使​​用新功能@singledispatch而不是类型检查,但我不知道如何保留前一个函数的类型提示:

旧功能:使用类型检查

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...

新功能:使用@singledispatch

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

...这样它就可以通过未来的 @singledispatch 注册进行扩展,但我无法让它工作。

我怎样才能添加Union[...]样式类型提示@singledispatch以可扩展的方式运行?


我想这就是你要找的。注意singledispatch需要register(type(None))代替register(None)。不支持register(Union[a, b]),但您可以应用多个register函数的装饰器...

import datetime
from functools import singledispatch
from typing import Union

MyDateTimeType = Union[
    int,
    None,
    datetime.datetime,
    datetime.date
]

@singledispatch
def to_unix_ts(date: MyDateTimeType) -> Union[int, None]:
    raise NotImplementedError

@to_unix_ts.register(int)
@to_unix_ts.register(type(None))
def _(date: Union[int, None]) -> Union[int, None]:
    return date

@to_unix_ts.register(str)
def _(date: str):
    # Handle string argument...

@to_unix_ts.register(datetime.datetime)
def _(date: datetime.datetime):
    # Handle datetime argument...

@to_unix_ts.register(datetime.date)
def _(date: datetime.date):
    # Handle date argument...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类型提示和@singledispatch:如何以可扩展的方式包含 `Union[...]`? 的相关文章

  • 将 ical 附件的邮件消息的内容类型设置为“text/calendar; method=REQUEST”

    我正在尝试使用 App Engine 邮件 API 从 App Engine 发送 iCalendar 格式的 ics 文件 这在 GMail 中非常有效 但是 Outlook 无法识别该文件 我认为问题在于内容类型设置为 文本 日历 而不
  • 在二维数组中进行所有可能的组合

    我正在尝试制作具有所有可能组合的 4x4 16 像素黑白图像数组 我制作了以下数组作为模板 template 0 0 0 0 start with all white pixels 0 0 0 0 0 0 0 0 0 0 0 0 然后我想迭
  • 函数名称未定义

    我有一段代码 看起来像这样 if name main main def main print hello 但是 当我尝试运行此代码时 出现错误 NameError 名称 main 未定义 我是否没有在函数 def main 的第一行定义名称
  • virtualenvwrapper 函数在 shell 脚本中不可用

    所以 我再一次制作了一个很棒的 python 程序 它让我的生活变得更加轻松 并节省了大量时间 当然 这涉及到一个 virtualenv 用mkvirtualenvvirtualenvwrapper 的功能 该项目有一个requiremen
  • 有什么好的适用于 Google App Engine 应用程序的 AJAX 框架吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在尝试在我的 Google App Engine 应用程序中实现 AJAX 因此我正在寻找一个好的
  • caffe安装:opencv libpng16.so.16链接问题

    我正在尝试在 Ubuntu 14 04 机器上使用 python 接口编译 caffe 我已经安装了 Anaconda 和 opencvconda install opencv 我还安装了咖啡中规定的所有要求 并更改了注释块makefile
  • 如何在Python + Selenium中获取元素的值

    我在我的 Python 3 6 3 代码中得到了这个 HTML 元素 作为 Selenium网页元素当然 span class ocenaCzastkowa masterTooltip style color 000000 alt 5 sp
  • Python 中“is”运算符的语义是什么?

    如何is运算符确定两个对象是否相同 它是如何工作的 我找不到它的记录 来自文档 http docs python org reference datamodel html 每个对象都有一个身份 一个类型 和一个值 对象的身份 一旦发生就永远
  • argparse 不检查位置参数

    我正在创建一个脚本 它使用 argparse 接受位置参数和可选参数 我已经阅读了 Doug 的教程和 python 文档 但找不到答案 parser argparse ArgumentParser description script t
  • 尝试校准keras模型

    我正在尝试通过 Sklearn 实现来校准我的 CNN 模型CalibratedClassifierCV 尝试将其包装为KerasClassifier并覆盖预测功能但没有成功 有人可以说我做错了什么吗 这是模型代码 def create m
  • Python FTP下载550错误

    我编写了一个 ftp 爬虫来下载特定文件 它会一直工作 直到找到要下载的特定文件 然后抛出此错误 ftplib error perm 550 该文件存在于我的下载文件夹中 但文件大小为 0 kb 我需要转换某些内容才能下载吗 我可以访问 f
  • 提高光线追踪命中功能的性能

    我有一个简单的 python 光线追踪器 渲染 200x200 的图像需要 4 分钟 这对于我的口味来说绝对是太多了 我想改善这种情况 几点 我为每个像素发射多条光线 以提供抗锯齿功能 每个像素总共发射 16 条光线 200x200x16
  • matplotlib vlines 图中未应用 y 轴的最小值

    我正在 matplotlib 中绘制 vlines 图 数据集中的所有 y 值如下 gt 0 我希望 y 轴最底部的刻度能够读取0 但相反 我得到 500 这是代码 usr bin env python import numpy as np
  • Pygame:有人可以帮我实现双跳吗?

    我知道已经有其他关于此问题的帖子了 但我的运动系统与我发现的有点不同 所以随后我问这个问题 我的运动系统基于一个名为的命名元组Move up left right down 然后就是这个 def update self move block
  • 为什么我无法杀死 k8s pod 中的 python 进程?

    我试图杀死一个 python 进程 ps aux grep python root 1 12 6 2 1 2234740 1332316 Ssl 20 04 19 36 usr bin python3 batch run py root 4
  • 解析整数集的字符串并列出间隔

    I have 2 5 7 9 12 string 我想从中获取 2 5 7 8 9 12 列表 python中有没有内置的函数 Thanks UPD 我想 直接的答案是No 不管怎样 谢谢你的 片段 使用一个 建议者斯文 马尔纳克 s 2
  • 如何在类型提示中定义元组或列表的大小

    有没有办法在参数的类型提示中定义元组或列表的大小 目前我正在使用这样的东西 from typing import List Optional Tuple def function name self list1 List Class1 if
  • 如何创建简单的梯度下降算法

    我正在研究简单的机器学习算法 从简单的梯度下降开始 但在尝试用 python 实现它时遇到了一些麻烦 这是我试图重现的示例 我获得了有关房屋的数据 居住面积 以英尺为单位 和卧室数量 以及最终的价格 居住面积 英尺2 2104 卧室 3 价
  • 如何仅读取 CSV 文件每行的第一列 [重复]

    这个问题在这里已经有答案了 如何在Python中读取CSV文件每行的第一列 我的数据是这样的 1 abc 2 bcd 3 cde 我只需要循环第一列的值 另外 当我在 calc 中打开 csv 文件时 每行中的数据都在同一个单元格中 这正常
  • 如何使 Django 自定义管理命令参数不再需要?

    我正在尝试在 django 中编写自定义管理命令 如下所示 class Command BaseCommand def add arguments self parser parser add argument delay type int

随机推荐