从函数的关键字参数生成 TypedDict

2023-11-26

foo.py:

kwargs = {"a": 1, "b": "c"}

def consume(*, a: int, b: str) -> None:
    pass

consume(**kwargs)

mypy foo.py:

error: Argument 1 to "consume" has incompatible type "**Dict[str, object]"; expected "int"
error: Argument 1 to "consume" has incompatible type "**Dict[str, object]"; expected "str"

这是因为object是一个超类型int and str,并因此推断。如果我声明:

from typing import TypedDict

class KWArgs(TypedDict):
    a: int
    b: str

然后注释kwargs as KWArgs, the mypy检查通行证。这实现了类型安全,但需要我复制关键字参数名称和类型consume in KWArgs。有没有办法生成这个TypedDict从类型检查时的函数签名,这样我就可以最大限度地减少维护中的重复?


To the best of my knowledge, there is no direct workaround on this [1], but there is another elegant way to achieve exactly that:

我们可以利用typings NamedTuple创建一个保存参数的对象:

ConsumeContext = NamedTuple('ConsumeContext', [('a', int), ('b', str)])

现在我们定义consume方法接受它作为参数:

def consume(*, consume_context : ConsumeContext) -> None:
    print(f'a : {consume_context.a} , b : {consume_context.b}')

整个代码是:

from typing import NamedTuple

ConsumeContext = NamedTuple('ConsumeContext', [('a', int), ('b', str)])

def consume(*, consume_context : ConsumeContext) -> None:
    print(f'a : {consume_context.a} , b : {consume_context.b}')

ctx = ConsumeContext(a=1, b='sabich')

consume(consume_context=ctx)

运行 mypy 会产生:

Success: no issues found in 1 source file

它会认识到a and b是参数,并批准这一点。

运行代码将输出:

a : 1 , b : sabich

然而,如果我们改变b如果不是字符串,mypy 会抱怨:

foo.py:9: error: Argument "b" to "ConsumeContext" has incompatible type "int"; expected "str"
Found 1 error in 1 file (checked 1 source file)

通过这种方式,我们通过定义一次方法的参数和类型来实现对方法的类型检查。

[1] Because if either defining TypedDict or function signature, based on the other, would require to know the other's __annotations__, which is not known on check-time, and defining a decorator to cast types on run-time misses the point of type checking.

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

从函数的关键字参数生成 TypedDict 的相关文章

  • 如何使用 .pth 文件添加 Python 导入路径

    如果我将 pth 文件放入 site packages 中 则会给出一个ImportError 我不知道如何通过创建 pth 文件来导入 指在Python中导入 https stackoverflow com questions 69728
  • Pygame 让精灵按照给定的旋转行走

    很久以前我做了一个Scratch脚本 我想用Pygame将其转换为Python 有很多示例显示图像的旋转 但我想知道如何更改精灵的旋转以使其沿给定方向移动 而不更改图像 这是我的暂存代码 这是我的 Pygame 精灵类 class Star
  • 从 Python 将分层 JSON 数据写入 Excel xls?

    我想将一些数据从 python 写入 xlsx 我目前将其存储为 JSON 但它从 Python 中输出什么并不重要 单个文章的 JSON 如下所示 Word Count 50 Key Words Blah blah blah Foo Fr
  • Scrapy Splash,如何处理onclick?

    我正在尝试抓取以下内容 我能够收到响应 但我不知道如何访问以下项目的内部数据以抓取它 我注意到访问这些项目实际上是由 JavaScript 和分页处理的 这种情况我该怎么办 下面是我的代码 import scrapy from scrapy
  • Python ElementTree 获取带有命名空间的属性

    我试图访问 XML 中的 def 所以在这个例子中我会得到Evolus Common PlainTextV2作为输出 我似乎无法弄清楚如何获取具有名称空间的属性 如果我想得到id它工作得很好 Python for content ns in
  • 从 Spark 数据帧中过滤大量 ID

    我有一个大型数据框 其格式类似于 ID Cat date 12 A 201602 14 B 201601 19 A 201608 12 F 201605 11 G 201603 我需要根据大约 500 万个 Is 的列表来过滤行 最直接的方
  • 如何在每次运行 python 程序时添加新列

    我希望我的表的第一列作为卷号 第二列作为名称 每当我运行 python 程序时 我想在表中添加一列日期 在这个新列中 我想填充从 user list 获得的列表将包含值 P A P P 等 如何处理 我尝试首先通过 alter 命令添加一列
  • 检查列表是否已排序的 Pythonic 方法

    有没有一种Python式的方法来检查列表是否已经排序ASC or DESC listtimestamps 1 2 3 5 6 7 就像是isttimestamps isSorted 返回True or False 我想输入一些消息的时间戳列
  • 多个列表和大小的所有可能排列

    在 python 中使用以下命令很容易计算简单的排列itertools permutations https docs python org 3 library itertools html itertools permutations 你
  • Python 中使用 globals() 的原因?

    Python 中有 globals 函数的原因是什么 它只返回全局变量的字典 这些变量已经是全局的 所以它们可以在任何地方使用 我只是出于好奇而问 试图学习Python def F global x x 1 def G print glob
  • telethon 库:如何通过电话号码添加用户

    我正在研究 Telegram 的 Telethon 库 它可以使用 Telegram API 充当 Telegram 客户端 重要提示 这是电报客户端 API https core telegram org telegram api 而不是
  • Python Tkinter 网格复选框

    我想知道是否有一种简单的方法可以使用 Tkinter 创建复选框网格 我正在尝试制作一个由 10 行和 10 列 即 100 个复选框 组成的网格 以便每行只能选择两个复选框 编辑 我正在使用带有spyder的python 2 7 到目前为
  • 安塞布尔 + 10.11.6

    我在 非常 干净地安装 10 11 6 时遇到了 Ansible 的奇怪问题 我已经安装了brew zsh oh my zsh Lil snitch 和1password 实际上没有安装其他任何东西 我安装了ansible brew ins
  • 在 Python 中将嵌套字典位置作为参数传递

    如果我有一个嵌套字典 我可以通过索引来获取键 如下所示 gt gt gt d a b c gt gt gt d a b c 我可以将该索引作为函数参数传递吗 def get nested value d path a b return d
  • 获取 python 模块的 2 个独立实例

    我正在与以非 OO 方式编写的 python 2 x API 进行交互 它使用模块全局范围来处理一些内部状态驱动的东西 在它不再是单例的情况下需要它 并且修改原始代码 不是我们的 不是一个选择 如果不使用单独解释器的子进程运行 有什么方法可
  • 访问影子 DOM 中的元素

    是否有可能查找 Shadow DOM 中的元素与蟒蛇硒 示例用例 我有这个input with type date
  • Django 按小时过滤

    我找到了那个链接 http code djangoproject com attachment ticket 8424 time filters diff http code djangoproject com attachment tic
  • gnuplot:第 1 行:无效命令

    stackoverflow 上可爱的人们大家好 我正在尝试使用 gnuplot 绘制数据 我首先阅读表格并提取我想要的数据 我将此数据写入 dat 文件 截至目前 我只是尝试通过命令行绘制它 但会添加必要的代码以在 python 脚本工作后
  • AES 在 cryptojs 中加密并在 python Crypto.Cipher 中解密

    使用 js CryptoJS 加密并使用 python crypto Cipher 解密时出现问题 这是我在js中的实现 附加 iv 与加密消息并使用 base64 进行编码
  • 如何从Python枚举类中获取所有值?

    我正在使用 Enum4 库创建一个枚举类 如下所示 class Color Enum RED 1 BLUE 2 我要打印 1 2 作为某处的列表 我怎样才能实现这个目标 您可以执行以下操作 e value for e in Color

随机推荐