Python模块导入:单线与多线

2024-04-25 23:53:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

from module import a, b, c, d

还有这个

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

对我来说,压缩代码并使用第一个示例是有意义的,但我在第二个示例中看到了一些代码示例。有什么区别吗?还是程序员的偏好不同


Tags: 模块代码fromimport示例程序员意义module
3条回答

根本没有区别。它们的功能完全相同

然而,从文体的角度来看,一个可能比另一个更可取。在这一点上,PEP-8 for imports表示应该将from module 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

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

拆分行

为了缓解上述担忧,这样做可能更明智

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

如果第二行未与第一行一起删除,而仍保持单数import语句,则会导致错误

我建议不要盲目地遵循PEP-8。当你有大约一半的屏幕导入量时,事情开始变得不舒服,PEP-8与PEP-20的可读性指南发生冲突

我的偏好是

  1. 将所有内置导入放在一行上,如sys、os、time等
  2. 对于其他导入,每个包使用一行(不是模块)

上面提供了良好的平衡,因为读者仍然可以快速浏览依赖项,同时实现合理的紧凑性

比如说,

我的偏好

# 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建议

# 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

为了补充从inspectorG4dget's answer中提出的一些问题,当文件夹结构开始深度嵌套或模块名称不明确时,还可以使用元组进行多行导入

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,
)

这也行得通,尽管我不喜欢这种风格:

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

相关问题 更多 >