Pep 8 冲突,导入超过 72 个字符

Pep 8 Conflict, Imports exceed 72 characters

Python 中关于长导入语句的最佳实践是什么? Pep 8 允许 72-99 个字符的长行,但我发现我经常超过这个限制,当我努力格式化我的代码的其余部分时,这是一种耻辱。

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters.

来源:https://www.python.org/dev/peps/pep-0008/

当然,现在您可以只导入整个包。即 import numpy as np,但是我通常希望尽可能缩短导入时间以避免减少加载时间。

通常可以通过在表达式两边加上括号来避免超出限制。如果有括号,您可以根据需要将其中的表达式分成任意多行。另一种不太理想的方法是以反斜杠字符结束一行,这会导致忽略后面的换行符。

PEP 8 的 Maximum Line Length 部分对此进行了解释。