__future__如何分组?

时间:2021-01-22 19:57:02

According to PEP 8:

根据PEP 8:

Imports should be grouped in the following order:

进口应按以下顺序分组:

  1. standard library imports
  2. 标准库进口
  3. related third party imports
  4. 相关第三方进口
  5. local application/library specific imports
  6. 本地应用程序特定进口/库

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

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

But it does not mention about __future__ imports. Should __future__ imports be grouped together with standard library imports or separated from standard library imports.

但它没有提及进口的问题。应该将__future__导入与标准库导入组合在一起,或者与标准库导入分离。

So, which is more preferred:

所以,哪种更可取:

from __future__ import absolute_import
import sys
import os.path

from .submod import xyz

or:

或者:

from __future__ import absolute_import

import sys
import os.path

from .submod import xyz

1 个解决方案

#1


10  

I personally separate them. A __future__ import isn't just binding a name like other imports, it changes the meaning of the language. With things like from __future__ import division the module will likely run fine both with and without the import, but give different (wrong) results at places that have nothing telling me to go look at names imported if I want to know more about where they come from. __future__ imports should stand out as much as possible.

我个人分开。__future__导入不仅仅像其他导入一样绑定一个名称,它还会改变语言的含义。对于类似于__future__ import division这样的东西,模块可以在有导入和没有导入的情况下正常运行,但是如果我想知道它们来自哪里,那么在那些没有任何提示的地方给出不同(错误)的结果。进口应尽可能突出。

Also, I generally sort imports within a group alphabetically (no particularly good reason for doing that; I just find it has some very small benefits to diffs and merging branches), and __future__ imports have to be first, so I put them in their own group.

此外,我通常按字母顺序对组中的导入进行排序(这样做没有特别好的理由;我只是发现它对分散和合并分支有一些非常小的好处),并且__future__进口必须是首先的,所以我把它们放在他们自己的组中。

#1


10  

I personally separate them. A __future__ import isn't just binding a name like other imports, it changes the meaning of the language. With things like from __future__ import division the module will likely run fine both with and without the import, but give different (wrong) results at places that have nothing telling me to go look at names imported if I want to know more about where they come from. __future__ imports should stand out as much as possible.

我个人分开。__future__导入不仅仅像其他导入一样绑定一个名称,它还会改变语言的含义。对于类似于__future__ import division这样的东西,模块可以在有导入和没有导入的情况下正常运行,但是如果我想知道它们来自哪里,那么在那些没有任何提示的地方给出不同(错误)的结果。进口应尽可能突出。

Also, I generally sort imports within a group alphabetically (no particularly good reason for doing that; I just find it has some very small benefits to diffs and merging branches), and __future__ imports have to be first, so I put them in their own group.

此外,我通常按字母顺序对组中的导入进行排序(这样做没有特别好的理由;我只是发现它对分散和合并分支有一些非常小的好处),并且__future__进口必须是首先的,所以我把它们放在他们自己的组中。