typing-only-standard-library-import (TC003)
源自 flake8-type-checking 代码检查器。
有时提供修复。
作用
检查仅用于类型注解,但未在类型检查块中定义的标准库导入。
为什么这不好?
未使用的导入会增加运行时性能开销,并可能导致导入循环。如果导入仅用于类型相关的上下文中,则可以改为在 if TYPE_CHECKING:
块下有条件地导入,以最大限度地减少运行时开销。
如果 lint.flake8-type-checking.quote-annotations
设置为 true
,则注解将被包裹在引号中,如果这样做可以使相应的导入移动到 if TYPE_CHECKING:
块中。
如果一个类需要在运行时使用类型注解(例如 Pydantic、SQLAlchemy 和其他库),请考虑使用 lint.flake8-type-checking.runtime-evaluated-base-classes
和 lint.flake8-type-checking.runtime-evaluated-decorators
设置将它们标记为如此。
示例
from __future__ import annotations
from pathlib import Path
def func(path: Path) -> str:
return str(path)
建议改为
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
def func(path: Path) -> str:
return str(path)
预览
当 preview 启用时,如果 lint.future-annotations
设置为 true
,则如果这样做可以使导入移动到 if TYPE_CHECKING:
块中,将会添加 from __future__ import annotations
。如果同时启用这两个设置,这将优先于上面描述的 lint.flake8-type-checking.quote-annotations
设置。
Options (选项)
lint.flake8-type-checking.quote-annotations
lint.flake8-type-checking.runtime-evaluated-base-classes
lint.flake8-type-checking.runtime-evaluated-decorators
lint.flake8-type-checking.strict
lint.typing-modules
lint.future-annotations