typing-only-first-party-import (TC001)
源自 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 . import local_module
def func(sized: local_module.Container) -> int:
return len(sized)
建议改为
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from . import local_module
def func(sized: local_module.Container) -> int:
return len(sized)
预览
当 预览 启用时,确定导入是否为第一方的标准更加严格,这可能会影响此检查是否被触发,以及 TC001
是否被触发。请参阅 此常见问题解答部分 了解更多详情。
如果 lint.future-annotations
设置为 true
,则 from __future__ import annotations
将被添加,如果这样做可以将导入移动到 if TYPE_CHECKING:
块中。如果两个设置都启用,这将优先于上面描述的 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