跳转到主要内容

一个帮助您编写整洁导入的flake8插件。

项目描述

https://img.shields.io/github/actions/workflow/status/adamchainz/flake8-tidy-imports/main.yml?branch=main&style=for-the-badge https://img.shields.io/pypi/v/flake8-tidy-imports.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

一个帮助您编写整洁导入的flake8插件。

需求

支持Python 3.8到3.12。

安装

首先,使用

pip

安装

python -m pip install flake8-tidy-imports

其次,如果您定义了Flake8的select设置,请向其中添加I25前缀。否则,插件默认应该处于活动状态。


正在使用Django项目进行代码检查?请查看我的书籍Boost Your Django DX,其中涵盖了Flake8和其他许多代码质量工具。


选项

banned-modules

为规则I251(以下)配置。应包含一个映射,其中每行都是一个禁止的导入字符串,后面跟一个‘=’,然后是在遇到该导入时使用的消息。

还有一个特殊的指令,用于禁止Python 2和Python 3之间预选的移除/移动模块列表,在可能的情况下推荐来自six的替换。可以通过将{python2to3}添加到banned-modules列表中打开。

例如在 setup.cfg

[flake8]
banned-modules =
  mock = Use unittest.mock.
  {python2to3}

请注意,尽管名称如此,您也可以禁止导入的对象,因为语法相同。例如

[flake8]
banned-modules =
  decimal.Decimal = Use ints and floats only.

包含 * 的条目被视为匹配零个或多个路径组件的通配符。例如

  • example.yellow.* 匹配 example.yellowexample.yellow.truckexample.yellow.truck.driving 等。

  • example.*.truck 匹配 example.truckexample.yellow.truckexample.red.truckexample.big.red.truck 等。

ban-relative-imports

控制规则 I252(如下)。接受两个值

  • parents - 禁止从父模块(以及祖父母等)导入,即包含多个 . 的。

  • true - 禁止所有相对导入。

例如

[flake8]
ban-relative-imports = parents

(如果您想禁止绝对导入,可以将您项目的模块放在 banned-modules 中。)

规则

注意:在 4.0.0 版本之前,规则代码比现在低 50,例如 I250 是 I200。由于与 flake8-import-order 冲突,它们在 问题 #106 中进行了更改。

I250: 无用的导入别名

对三种形式的无需导入别名提出异议

  • import foo as foo -> import foo

  • import foo.bar as bar -> from foo import bar

  • from foo import bar as bar -> from foo import bar

信息包括建议的重新编写(这可能 不一定 是正确的),例如

$ flake8 file.py
file.py:1:1: I250 Unnecessary import alias - rewrite as 'from foo import bar'.

可以通过激活其 remove_redundant_aliases 选项 来自动修复此类别名。

I251: 禁止的导入 <import> 使用。

对使用禁止导入提出异议。默认情况下,没有禁止导入 - 您应该根据上面在“选项”中描述的“banned-modules”进行配置。

信息包括来自配置的用户定义部分。例如

$ flake8 file.py
file.py:1:1: I251 Banned import 'mock' used - use unittest.mock instead.

I252: 禁止使用相对导入 <从父模块导入>

对使用相对导入提出异议

  • from . import foo(兄弟导入)

  • from .bar import foo(兄弟导入)

  • from .. import foo(父导入)

ban-relative-imports 配置选项控制。

绝对导入或从兄弟导入的相对导入由 PEP8 推荐使用。

绝对导入建议使用,因为它们通常更易读,并且表现更好...

import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

然而,显式的相对导入是绝对导入的可接受替代方案...

from . import sibling
from .sibling import example

另请参阅

要更高级地控制您项目中的导入,请尝试 import-linter

由以下提供支持