PEP8建议:
导入应按以下顺序分组:
您应该在每组导入之间放置一个空行。
有没有办法使用pylint、pyflakes、pychecker、pep8等静态代码分析工具来检查包中的任何地方是否违反了标准
违规示例:
from my_package import my_module
from django.db import models
import os正确的导入方式:
import os
from django.db import models
from my_package import my_module发布于 2016-02-05 07:00:48
pylint的当前版本现在可以做到这一点,并将其报告为错误类C0411。
发布于 2014-04-01 04:17:38
更新(2016):sbywater有最新的答案。
找到了!(无意中阅读“python黑客指南”)
名为hacking的OpenStack黑客风格检查项目引入了几个独特的flake8扩展。其中就有相关的commit( hacking_import_groups )。
示例:
python $ git克隆https://github.com/openstack-dev/hacking.git $ cd hacking/ $
- [tox](http://tox.readthedocs.org/en/latest/)
- [flake8](https://flake8.readthedocs.org/en/latest/)
- [hacking](https://github.com/openstack-dev/hacking/) (from the master branch):setup.py安装
示例中使用的
检查本地黑客行为-
- `tox.ini` (we need to tell flake8 that we want to use a custom check)= hacking.core.hacking_import_groups
更新:在最新版本的hacking中,检查的路径已更改,现在为hacking.checks.imports.hacking_import_groups。
- test.py (检查的目标)
导入请求从my_module导入系统导入print_smth print_smth(requests.get('https://google.com')) print_smth(sys.version)
- my_module.py (test.py使用的本地导入)
def print_smth( smth ):打印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
$希望这能对将来的人有所帮助。
发布于 2014-04-01 22:39:38
了解一下https://pypi.python.org/pypi/isort或https://github.com/timothycrosley/isort
isort为全局级导入行解析指定的文件(在try / excepts块、函数等外部导入)并将它们全部放在文件的顶部,按导入类型分组:
自定义独立的部分(由配置文件中的forced_separate列表定义)在每个部分中,导入按字母顺序排序。isort自动删除重复的python导入,并将long从导入换行到指定的行长(默认为80)。
https://pypi.python.org/pypi/flake8-isort将此功能插入到flake8中
https://stackoverflow.com/questions/22722976
复制相似问题