typing-only-third-party-import (TC002)
源自 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
import pandas as pd
def func(df: pd.DataFrame) -> int:
return len(df)
建议改为
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import pandas as pd
def func(df: pd.DataFrame) -> int:
return len(df)
预览
当启用预览时,用于确定导入是否为第一方的标准会更加严格,这可能会影响此 lint 是否被触发,相对于 TC001
。 参见此 FAQ 部分 以了解更多详情。
如果 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