跳转到主要内容

一个命令行界面和预提交钩子,用于将类型注解语法升级到PEP 585和PEP 604

项目描述

fix-future-annotations

一个命令行界面和预提交钩子,用于将类型注解语法升级到PEP 585和PEP 604。

升级详情

PEP 585 – 标准集合中的类型提示泛型

旧版本新版本
typing.Dict[str, int]
List[str]
dict[str, int]
list[str]

PEP 604 – 允许以 X | Y 的形式编写联合类型

旧版本新版本
typing.Union[str, int]
Optional[str]
str | int
str | None

PEP 563 – 延迟评估注解

旧版本新版本
def create() -> "Foo": pass
def create() -> Foo: pass

导入别名处理

旧版本新版本
import typing as t
from typing import Tuple as MyTuple

def foo() -> MyTuple[str, t.Optional[int]]:
    pass
from __future__ import annotations

import typing as t

def foo() -> tuple[str, int | None]:
    pass

完整示例

旧版本新版本
from typing import Union, Dict, Optional, Tuple

# non-annotation usage will be preserved
MyType = Union[str, int]


def foo() -> Tuple[Dict[str, int], Optional[str]]:
    ...
from __future__ import annotations

from typing import Union

# non-annotation usage will be preserved
MyType = Union[str, int]


def foo() -> tuple[dict[str, int], str | None]:
    ...

未使用的导入名称将被删除,如果脚本中没有找到 from __future__ import annotations,并且正在使用新语法,则将自动添加。

作为命令行工具使用

python3 -m pip install -U fix-future-annotations

fix-future-annotations my_script.py

作为预提交钩子使用

将以下内容添加到您的 .pre-commit-config.yaml

repos:
  - repo: https://github.com/frostming/fix-future-annotations
    rev: x.y.z  # a released version tag
    hooks:
      - id: fix-future-annotations

配置

fix-future-annotations 可以通过 pyproject.toml 进行配置。以下是一个示例

[tool.fix_future_annotations]
exclude_files = [  # regex patterns to exclude files
    'tests/.*',
    'docs/.*',
]

exclude_lines = [  # regex patterns to exclude lines
    '# ffa: ignore',   # if a line ends with this comment, the whole *block* will be excluded
    'class .+\(BaseModel\):'  # classes that inherit from `BaseModel` will be excluded
]

许可证

此作品根据 MIT 许可证分发。

项目详情


下载文件

下载适合您平台文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分布

fix-future-annotations-0.5.0.tar.gz (11.3 kB 查看哈希值)

上传于 源码

构建分发

fix_future_annotations-0.5.0-py3-none-any.whl (10.1 kB 查看哈希值)

上传于 Python 3

由以下机构支持