简体   繁体   English

Python 模块导入:单行与多行

[英]Python Module Import: Single-line vs Multi-line

When importing modules in Python, what is the difference between this: Python导入模块时,这有什么区别:

from module import a, b, c, d

and this和这个

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.它们的功能完全相同。

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:在那一点上,导入PEP-8说你应该将from module import name1, name2压缩到一行,并将import module1保留在多行上:

Yes: import os
     import sys

No:  import sys, os

Ok: from subprocess import Popen, PIPE

In response to @teewuane's comment (repeated here in case the comment gets deleted):回应@teewuane 的评论(如果评论被删除,请在此处重复):

@inspectorG4dget What if you have to import several functions from one module and it ends up making that line longer than 80 char? @inspectorG4dget 如果您必须从一个模块导入多个函数并且最终使该行长度超过 80 个字符怎么办? 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.我知道 80 个字符是“当它使代码更具可读性时”,但我仍然想知道是否有更整洁的方法来做到这一点。 And I don't want to do from foo import * even though I am basically importing everything.而且我不想从 foo import * 做,即使我基本上是导入所有东西。

The issue here is that doing something like the following could exceed the 80 char limit:这里的问题是,执行以下操作可能会超出 80 个字符的限制:

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

To this, I have two responses (I don't see PEP8 being overly clear about this):对此,我有两个回应(我不认为 PEP8 对此过于明确):

Break it up into two imports :把它分成两个进口

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

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.这样做的缺点是,如果module从代码库中删除或以其他方式重构,则需要删除两个导入行。 This could prove to be painful这可能会很痛苦

Split the line :分割线

To mitigate the above concern, it may be wiser to do为了减轻上述担忧,可能更明智的做法是

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

This would result in an error if the second line is not deleted along with the first, while still maintaining the singular import statement如果第二行没有与第一行一起删除,同时仍然保持单一的导入语句,这将导致错误

To add to some of the questions raised from inspectorG4dget's answer , you can also use tuples to do multi-line imports when folder structures start getting deeply nested or you have modules with obtuse names.为了补充从inspectorG4dget的回答中提出的一些问题,当文件夹结构开始深度嵌套或者您有名称不明确的模块时,您还可以使用元组进行多行导入。

from some.module.submodule.that_has_long_names import (
    first_item,
    second_item,
    more_imported_items_with_really_enormously_long_names_that_might_be_too_descriptive,
    that_would_certainly_not_fit,
    on_one_line,
)

This also works, though I'm not a fan of this style:这也有效,尽管我不喜欢这种风格:

from module import (a_ton, of, modules, that_seem, to_keep, needing,
                    to_be, added, to_the_list, of_required_items)

I would suggest not to follow PEP-8 blindly.我建议不要盲目遵循 PEP-8。 When you have about half screen worth of imports, things start becoming uncomfortable and PEP-8 is then in conflicts with PEP-20 readability guidelines.当你有大约一半的屏幕导入时,事情开始变得不舒服,然后 PEP-8 与 PEP-20 可读性指南发生冲突。

My preference is,我的偏好是,

  1. Put all built-in imports on one line such as sys, os, time etc.将所有内置导入如 sys、os、time 等放在一行。
  2. For other imports, use one line per package (not module)对于其他导入,每个包使用一行(不是模块)

Above gives you good balance because the reader can still quickly glance the dependencies while achieving reasonable compactness.上面给了你很好的平衡,因为读者仍然可以快速浏览依赖项,同时实现合理的紧凑性。

For example,例如,

My Preference我的偏好

# one line per package

import os, json, time, sys, math
import numpy as np
import torch, torch.nn as nn, torch.autograd, torch.nn.functional as F
from torchvision models, transforms

PEP-8 Recommandation PEP-8 推荐

# one line per module or from ... import statement

import os
import json
import time
import sys
import math

import numpy as np

import torch
from torch import nn as nn, autograd, nn.functional as F
from torchvision import models, transforms

A concern not mentioned by other answers is git merge conflicts.其他答案未提及的问题是 git 合并冲突。

Let's say you start with this import statement:假设您从这个导入语句开始:

import os

If you change this line to import os, sys in one branch and import json, os in another branch, you will get this conflict when you attempt to merge them:如果您将此行更改为在一个分支中import os, sys并在另一个分支中import json, os ,则当您尝试合并它们时将遇到此冲突:

<<<<<<< HEAD
import os, sys
=======
import json, os
>>>>>>> branch

But if you add import sys and import json on separate lines, you get a nice merge commit with no conflicts:但是如果你在不同的行中添加import sysimport json ,你会得到一个没有冲突的很好的合并提交:

--- a/foo.py
+++ b/foo.py
@@@ -1,2 -1,2 +1,3 @@@
+ import json
  import os
 +import sys

You will still get a conflict if the two imports were added at the same location, as git doesn't know which order they should appear in. So if you had imported time instead of json , for example:如果将两个导入添加到同一位置,您仍然会发生冲突,因为 git 不知道它们应该按哪个顺序出现。因此,如果您导入的是time而不是json ,例如:

import os
<<<<<<< HEAD
import sys
=======
import time
>>>>>>> branch

Still, it can be worth sticking with this style for the occasions where it does avoid merge conflicts.尽管如此,在确实避免合并冲突的情况下,还是值得坚持使用这种风格。

Imports should usually be on separate lines as per PEP 8 guidelines.根据 PEP 8 指南,导入通常应位于单独的行上。

# Wrong Use
import os, sys
# Correct Use
import os
import sys

For more import based PEP 8 violations and fixes please check this out https://ayush-raj-blogs.hashnode.dev/making-clean-pr-for-open-source-contributors-pep-8-style .有关更多基于导入的 PEP 8 违规和修复,请查看https://ayush-raj-blogs.hashnode.dev/making-clean-pr-for-open-source-contributors-pep-8-style

both are same.两者都是一样的。 use from module import a, b, c, d .使用from module import a, b, c, d

If u want to import only one part of a module, use from module import a , if u want to import multiple codes from same module, use from module import a,b,c,d .如果您只想导入模块的一部分,请使用from module import a ,如果您想从同一模块导入多个代码,请使用from module import a,b,c,d Why to write all in seperate lines when both are same.当两者都相同时,为什么要将所有内容都写在单独的行中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM