【问题标题】:Pylint complains when importing in the right order按正确顺序导入时 Pylint 抱怨
【发布时间】:2022-01-16 23:35:44
【问题描述】:

我认为 Python 中正确的导入顺序是问题的第一个答案所描述的顺序:What's the correct way to sort Python `import x` and `from x import y` statements?

因此,这段代码应该是正确的:

import os
import time
import yaml

from collections import OrderedDict
from xtesting.core import testcase

但是,当我运行 Pylint 时,我得到:

C:  5, 0: standard import "from collections import OrderedDict" should be placed before "import yaml" (wrong-import-order)

所以我猜“yaml”不是标准库。那么正确的方法应该是这个(即使它更丑陋且可读性差)?

import os
import time
from collections import OrderedDict
import yaml

from xtesting.core import testcase

【问题讨论】:

  • yaml 默认情况下不会出现,Pep 是一个建议,请使用您认为更符合您的代码库的任何内容。

标签: python pylint


【解决方案1】:

PyYAML 不是标准 Python 库的一部分,它从标准库导入,无论是通用 (import os) 还是特定 (from collections import OrderedDict) 都应该放在首位。

IMO,您应该按字典顺序对部分中的模块名称进行排序,并用空行分隔部分:

from collections import OrderedDict
import os
import time

from xtesting.core import testcase
import yaml

有些人希望在每个部分中都将通用的放在首位:

import os
import time
from collections import OrderedDict

import yaml
from xtesting.core import testcase

这看起来更好,但它更容易在较长的通用列表之后忽略特定的导入。它还将通用和特定导入从一个相同的模块中分离出来,这在 IMO 中是不好的:

import yaml
from xtesting.core import testcase
from yaml import safe_load

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 2017-03-29
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    相关资源
    最近更新 更多