typing-only-third-party-import (TC002)
源自 flake8-type-checking 代码检查器。
有时提供修复。
作用
检查仅用于类型注解但未在类型检查代码块中定义的第三方导入。
为什么这不好?
未使用的导入会增加运行时的性能开销,并存在产生循环导入的风险。如果某个导入仅在仅类型(typing-only)上下文中使用,则可以将其改为在 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 设置将其标记为此类。
如果 lint.future-annotations 设置为 true,且这样做能使某个导入被移动到 if TYPE_CHECKING: 块中,则会添加 from __future__ import annotations。如果上述两个设置均已启用,则此设置的优先级高于 lint.flake8-type-checking.quote-annotations。
示例
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)
Options (选项)
lint.flake8-type-checking.quote-annotationslint.flake8-type-checking.runtime-evaluated-base-classeslint.flake8-type-checking.runtime-evaluated-decoratorslint.flake8-type-checking.strictlint.typing-moduleslint.future-annotations