Python 模块导入:单行 vs 多行 [英] Python Module Import: Single-line vs Multi-line

查看:44
本文介绍了Python 模块导入:单行 vs 多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中导入模块时,这有什么区别:

When importing modules in Python, what is the difference between this:

from module import a, b, c, d

还有这个

from module import a
from module import b
from module import c
from module import d

对我来说,压缩代码并使用第一个示例总是有意义的,但我一直在看到一些代码示例,第二个.到底有什么区别还是全在于程序员的喜好?

To me it makes sense always to condense code and use the first example, but I've been seeing some code samples out there dong the second. Is there any difference at all or is it all in the preference of the programmer?

推荐答案

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

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

这篇关于Python 模块导入:单行 vs 多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆