在python中分组导入语句

2024-05-29 10:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始学习python,并在python文件上运行pylint。我得到以下评论。在

from os import listdir
from os.path import isfile, join

我在上面两行,Pylinter的评论是

^{pr2}$

我怎么才能做到呢?在

下面是另一条评论

import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests

C:  5, 0: standard import "import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests" should be placed before "import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests" (wrong-import-order)

上面这条线是什么意思?为什么需要它?在


Tags: csvdjangoimportuuidtimeosloggingsys
1条回答
网友
1楼 · 发布于 2024-05-29 10:34:27

PEP8建议按如下方式对导入进行排序和分组:

Imports should be grouped in the following order:

  1. Standard library imports.

  2. Related third party imports.

  3. Local application/library specific imports.

You should put a blank line between each group of imports.

在您的例子中,django和requests是第三方导入,因此您应该编写

import mimetypes, time, csv, platform, base64, sys, os, math, uuid, linecache, logging

import django, requests

当您有这么多的导入时(在每个组中)按字母顺序排列可能会更有用。在

此外,pylint似乎更喜欢PEP8之外的分组。特别是,来自同一模块/包的导入应该组合在一起。也就是说,在您的os导入和其他导入之间添加一个空格,甚至可以将空的os导入也放在那里。总共:

^{pr2}$

相关问题 更多 >

    热门问题