【问题标题】:Difference between "from x.y import z" and "import x.y.z as z"“从 x.y 导入 z”和“将 x.y.z 导入为 z”之间的区别
【发布时间】:2018-05-11 19:37:39
【问题描述】:

在您想将嵌套模块导入命名空间的情况下,我总是这样写:

from concurrent import futures

但是,我最近意识到这也可以使用“as”语法来表达。请参阅以下内容:

import concurrent.futures as futures

哪个具有看起来更类似于其他进口产品的主观优势:

import sys
import os
import concurrent.futures as futures

... 缺点是冗长。

两者之间是否存在功能差异,或者是 PEP 或其他方面的官方首选?

【问题讨论】:

  • @chrisz:这涵盖了import modulefrom module import thing 之间的区别;它不包括import module.thing as thing
  • 请注意,import foo.bar as bar 仅在 foo.bar 本身是一个模块时才有效,而 from foo import bar 适用于 foo 中的 any 模块级名称。
  • as 的创建是为了避免具有相同名称的模块/libs/funcs 之间的冲突,另一个命名空间......
  • stackoverflow.com/questions/710551/… 重复,我在审核审核中遇到了问题:(

标签: python python-import


【解决方案1】:

存在一些功能差异。首先,正如 cmets 中已经提到的,import package.thing as thing 要求 thing 是一个模块(或子包,这实际上并不是一个单独的情况,因为包也算作模块)。

其次,在 Python 3.5 及更高版本中,如果 from package import thing 发现 package 的模块对象没有 thing 属性,它将尝试查找 sys.modules['package.thing'] 作为后备。 This was added 处理某些循环相对导入的情况。 import package.thing as thing 尚未执行此处理,但它在 Python 3.7 中为 will

【讨论】:

    【解决方案2】:
    import concurrent.futures as futures
    

    允许您在代码中引用 futures 命名空间下的模块(与没有 as 语法的 concurrent.futures 相对)。然而,打字大多是多余的——你正在导入一些东西并声明它的名字是完全相同的东西。这种导入的标准语法是from <package> import <module>

    关于您的问题的重点是as 语法主要是为了支持同名的多个导入而不会相互干扰。例如。

    from concurrent import futures
    from other.module import futures as my_futures
    

    如果你在滥用as 语法,对我来说,其他任何事情都将被视为反模式,因为该语言为你提供了一种正确的方式来做你想做的事。

    【讨论】:

    • as 在该示例中并不是严格冗余的,因为没有 asconcurrent 是在命名空间中引入的,而不是 futures
    • 不正确。当您import concurrent.futures 时,您需要将其寻址为conncurrent.futures。当您import concurrent.futures as futures 时,您将其寻址为futures
    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2018-08-12
    • 2012-08-29
    • 2012-10-07
    • 1970-01-01
    • 2019-04-18
    • 2011-06-22
    相关资源
    最近更新 更多