如何使用长名称的 pep8 正确导入

How to import correctly with pep8 with long names

您不应在 Python 中使用超过 80 个字符的行。但我想知道如何导入长行,例如

from .exceptions import PartsNotFitException, PartsmanagementException, CircleDetectedException

我在想

from .exceptions import PartsNotFitException
from .exceptions import PartsmanagementException
from .exceptions import CircleDetectedException

但这看起来有点奇怪。

您可以使用括号来允许换行:

from .exceptions import (
    PartsNotFitException,
    PartsmanagementException,
    CircleDetectedException
)

用括号将它们分成多行,它符合 PEP8(例如,将通过 pep8 命令)

from .exceptions import (
    PartsNotFitException,
    PartsmanagementException,
    CircleDetectedException,
)

我喜欢它的地方:

  • PEP8 兼容

  • 每行都有导入,很容易comment/uncomment一个给定的导入。

  • 并且在最后一次导入时使用尾随逗号 ,,您可以在末尾附加一个导入,而不会在前一行创建源代码管理差异,因为您不这样做稍后必须在上一行添加一个逗号。