对Python“import x”和“from x import y”语句进行排序的正确方法是什么?

2024-05-14 06:13:08 发布

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

python style guide建议将导入分组如下:

Imports should be grouped in the following order:

  1. standard library imports
  2. related third party imports
  3. local application/library specific imports

但是,它没有提到应如何安排这两种不同的进口方式:

from foo import bar
import foo

有多种方法可以对它们进行排序(假设所有这些导入都属于同一组):

  • 首先from..import,然后import

    from g import gg
    from x import xx
    import abc
    import def
    import x
    
  • 首先import,然后from..import

    import abc
    import def
    import x
    from g import gg
    from x import xx
    
  • 按模块名称按字母顺序排列,忽略导入的类型

    import abc
    import def
    from g import gg
    import x
    from xx import xx
    

PEP8没有提到这个特性的首选顺序,一些ide的“清除导入”特性可能只是做了开发人员喜欢做的事情。

我正在寻找另一个澄清这一点的PEP或来自BDFL的相关评论/电子邮件(或另一个Python核心开发人员)。请不要发表主观的答案说明你自己的偏好。


Tags: fromimportfoo开发人员styledeflibrary特性
3条回答

根据CIA的内部编码约定(作为WikiLeaks Vault 7 leak的一部分),python导入应该分为三组:

  1. 标准库导入
  2. 第三方进口
  3. 特定于应用程序的导入

导入应按字典顺序排列在这些组中,忽略大小写:

import foo
from foo import bar
from foo.bar import baz
from foo.bar import Quux
from Foob import ar

导入通常按字母顺序排序,并在PEP8旁边的不同位置进行描述。

按字母顺序排序的模块更易于阅读和搜索。毕竟,python是关于可读性的。 此外,更容易验证是否导入了某些内容,并避免重复导入

在PEP8中没有关于排序的内容,所以你要做的就是选择。

根据少数来自知名网站和知识库的参考资料,按字母顺序排序是一种方法。

例如:

import httplib
import logging
import random
import StringIO
import time
import unittest
from nova.api import openstack
from nova.auth import users
from nova.endpoint import cloud

或者

import a_standard
import b_standard

import a_third_party
import b_third_party

from a_soc import f
from a_soc import g
from b_soc import d

Reddit官方存储库还声明,一般来说,应该使用PEP-8导入顺序。不过,也有一些附加条款

for each imported group the order of imports should be:
import <package>.<module> style lines in alphabetical order
from <package>.<module> import <symbol> style in alphabetical order

参考文献:

注意:isort utility自动对导入进行排序。

政治公众人物8对此事只字未提。这一点没有约定,也不意味着Python社区绝对需要定义一个约定。一个选择对一个项目来说可能更好,但对另一个项目来说却是最坏的。。。这是一个偏好的问题,因为每个解决方案都有利弊。但如果你想遵循惯例,你必须尊重你引用的主要顺序:

  1. 标准库导入
  2. 关联第三方进口
  3. 本地应用程序/库特定导入

例如,Google recommend in this pagethatimport应该按照字典顺序在每个类别(标准/第三方/您的)中进行排序。但在Facebook、雅虎等公司,这可能是另一个惯例。。。

相关问题 更多 >