You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python是否支持通过两个TypedDict相减生成新类型注解?

Python中实现TypedDict的"减法"操作

Python标准库的TypedDict本身不直接支持类似集合的减法运算符,但可以通过几种方式实现你想要的“排除指定键生成新TypedDict”的效果,类似TypeScript里的Omit类型:

1. 手动定义新TypedDict(最直接)

如果场景简单,直接手动写出排除目标键后的新TypedDict即可,类型检查器完全支持:

from typing import TypedDict

class A(TypedDict):
    x: int
    y: int
    z: int

# 手动定义C,只保留A中不在B里的键
class C(TypedDict):
    x: int
    y: int

def f() -> C:
    return {'x': 0, 'y': 0}

2. 动态构造类型别名

可以通过读取TypedDict的__annotations__属性,过滤掉不需要的键,动态生成新的TypedDict类型别名:

from typing import TypedDict

class A(TypedDict):
    x: int
    y: int
    z: int

class B(TypedDict):
    z: int

# 过滤A的注解,排除B中存在的键
C = TypedDict('C', {k: v for k, v in A.__annotations__.items() if k not in B.__annotations__})

def f() -> C:
    return {'x': 0, 'y': 0}

这种方式适合键较多的场景,避免重复写代码,主流类型检查器(如mypy、pyright)都能正确识别这个动态生成的类型。

3. 利用类型检查器的扩展支持

部分类型检查器(如mypy)结合typing_extensions库,可以实现更接近TypeScript语法的类型操作,比如通过Unpack和类型构造工具,但本质还是基于键的过滤来模拟集合减法的效果。

需要注意的是,Python本身没有内置的“类型减法”语法糖,所有实现都是基于键的过滤来达成需求。

内容的提问来源于stack exchange,提问作者Michael Moreno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:50:30