没有任何区别。它们的功能完全相同。
然而,从风格上看,可能比另一个更可取。而在这一点上,PEP-8 for imports表示你应该从模块import name1,name2压缩到一行,并将import module1放在多行上:
Yes: import os
import sys
No: import sys, os
Ok: from subprocess import Popen, PIPE
响应@ teewuane的评论(重复这里,如果注释被删除):
@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个字符限制:
from module import func1, func2, func3, func4, func5
对此,我有两个答复(我看不到PEP8对此过于清楚):
将其分为两个进口:
from module import func1, func2, func3
from module import func4, func5
这样做的缺点是,如果将模块从代码库中移除或以其他方式重构,则需要删除两条导入行。这可能是痛苦的
拆分行:
为了减轻上述问题,可能会更明智
from module import func1, func2, func3, \
func4, func5
如果第二行不与第一行一起删除,同时仍然保留单个导入语句,则会导致错误