更新(2016):sbywater提供了最新的答案。
找到了!(偶然在阅读《Python黑客指南》时发现的)
OpenStack Hacking Style Checks项目名为hacking,引入了几个独特的flake8
扩展。其中有一个叫hacking_import_groups的扩展(相关的提交)。
示例:
$ git clone https://github.com/openstack-dev/hacking.git
$ cd hacking/
$ python setup.py install
示例中使用的文件
[hacking]
local-check = hacking.core.hacking_import_groups
更新:使用最新版本的hacking
后,检查路径已更改,现在为hacking.checks.imports.hacking_import_groups
。
test.py
(检查目标)
import requests
import sys
from my_module import print_smth
print_smth(requests.get('https://google.com'))
print_smth(sys.version)
my_module.py
(被test.py
使用的本地导入)
def print_smth(smth):
print smth
然后,如果我在test.py
上运行flake8
:
$ flake8 test.py
test.py:2:1: H305 imports not grouped correctly (requests: third-party, sys: stdlib)
test.py:3:1: H305 imports not grouped correctly (sys: stdlib, my_module.print_smth: project)
test.py:3:1: H306 imports not in alphabetical order (sys, my_module.print_smth)
然后,如果我按照PEP8
的正确顺序对导入进行分组:
import sys
import requests
from my_module import print_smth
print_smth(requests.get('https://google.com'))
print_smth(sys.version)
没有发现警告:
$ flake8 test.py
$
希望这会对未来的某个人有所帮助。
pep8
工具目前不会检查这个问题 - 它只会检查一行上的多个导入 (E401)。 - DNA