且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 模块导入:单行 vs 多行

更新时间:2022-04-16 08:37:32

完全没有区别.它们的功能完全相同.

There is no difference at all. They both function exactly the same.

但是,从风格的角度来看,一个可能比另一个更可取.在这一点上,用于导入的 PEP-8 说你应该压缩 from module import name1, name2 到一行,将 import module1 留在多行:

However, from a stylistic perspective, one might be more preferable than the other. And on that note, the PEP-8 for imports says that you should compress from module import name1, name2 onto a single line and leave import module1 on multiple lines:

Yes: import os
     import sys

No:  import sys, os

Ok: from subprocess import Popen, PIPE

回应@teewuane的评论(如果评论被删除,请在此处重复):

In response to @teewuane's comment (repeated here in case the comment gets deleted):

@inspectorG4dget 如果您必须从一个函数中导​​入多个函数怎么办模块,它最终使该行长于 80 个字符?我知道80 个字符是当它使代码更具可读性时",但我我仍然想知道是否有更整洁的方法来做到这一点.我不想做 from foo import * 即使我基本上是导入一切.

@inspectorG4dget What if you have to import several functions from one module and it ends up making that line longer than 80 char? I know that the 80 char thing is "when it makes the code more readable" but I am still wondering if there is a more tidy way to do this. And I don't want to do from foo import * even though I am basically importing everything.

这里的问题是执行以下操作可能会超出 80 个字符的限制:

The issue here is that doing something like the following could exceed the 80 char limit:

from module import func1, func2, func3, func4, func5

对此,我有两个回应(我不认为 PEP8 对此过于明确):

To this, I have two responses (I don't see PEP8 being overly clear about this):

将其分为两个导入:

from module import func1, func2, func3
from module import func4, func5

这样做的缺点是,如果 module 从代码库中删除或以其他方式重构,则需要删除两个导入行.这可能会很痛苦

Doing this has the disadvantage that if module is removed from the codebase or otherwise refactored, then both import lines will need to be deleted. This could prove to be painful

分割线:

为了减轻上述担忧,这样做可能更明智

To mitigate the above concern, it may be wiser to do

from module import func1, func2, func3, \
     func4, func5

如果第二行没有与第一行一起删除,同时仍然保持单一的import语句,这将导致错误

This would result in an error if the second line is not deleted along with the first, while still maintaining the singular import statement