跳到内容

unnecessary-default-type-args (UP043)

源自 pyupgrade linter。

修复总是可用的。

作用

检查 Python 3.13+ 上 GeneratorAsyncGenerator 的不必要的默认类型参数。

为什么这不好?

Python 3.13 引入了类型参数指定默认值的能力。在此更改之后,一些标准库类被更新,为其某些类型参数添加了默认值。例如,Generator[int] 现在等同于 Generator[int, None, None],因为 Generator 的第二个和第三个类型参数现在默认为 None

省略与默认值匹配的类型参数可以使代码更简洁,更易于阅读。

示例

from collections.abc import Generator, AsyncGenerator


def sync_gen() -> Generator[int, None, None]:
    yield 42


async def async_gen() -> AsyncGenerator[int, None]:
    yield 42

建议改为

from collections.abc import Generator, AsyncGenerator


def sync_gen() -> Generator[int]:
    yield 42


async def async_gen() -> AsyncGenerator[int]:
    yield 42

修复安全性

除非类型注解包含注释,否则此规则的修复被标记为安全。

Options (选项)

参考