Grouping import statements in python

ank*_*kit 5 python pylint

I have started learning python recently and ran pylint on my python file. I got following comments.

from os import listdir
from os.path import isfile, join
Run Code Online (Sandbox Code Playgroud)

I the above two lines, the Pylinter comment is

C:  5, 0: Imports from package os are not grouped (ungrouped-imports)
Run Code Online (Sandbox Code Playgroud)

How can I achieve that ?

And another comment is in below line

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)
Run Code Online (Sandbox Code Playgroud)

上面一行是什么意思,为什么需要它?

jmd*_*_dk 9

PEP8建议对导入进行排序和分组,如下所示:

进口应按以下顺序分组:

  1. 标准库导入。

  2. 相关的第三方进口。

  3. 本地应用程序/库特定的导入。

您应该在每组导入之间放置一个空行。

在你的情况下,django 和 requests 是第三方导入,所以你应该写

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

import django, requests
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

import django, requests 
Run Code Online (Sandbox Code Playgroud)

  • `import base64, csv, linecache, logging, math, mimetypes, platform, time, sys, uuid` 这是 PEP8 非常不鼓励的。这些都应该是单独的导入语句。PEP8:“导入通常应该在单独的行上:” (3认同)