“Python ‘import foo.bar as baz’ vs ‘from foo import bar as baz'”

huangapple go评论77阅读模式
英文:

Python "import foo.bar as baz" vs "from foo import bar as baz"

问题

这两种导入有区别吗,还是只是相同操作的语法糖?

import foo.bar as baz
# 对比
from foo import bar as baz

我尝试了两种方式,bazdir(baz) 的结果对于每种方式看起来都是相同的。

英文:

Is there a difference between these two imports, or are they just syntax sugar for the same thing?

import foo.bar as baz 
# vs
from foo import bar as baz

I tried both, and the results of

>>> baz

and

>>> dir(baz)

look identical for each.

答案1

得分: 3

import foo.bar as baz 需要 foo.bar 是一个模块。它不是执行属性查找的表达式,而是一个点号连接的单一名称。(最重要的是,并没有保证任何包将其模块作为属性暴露。import foo 并不保证 foo.bar 评估为包 foo 中包含的模块 bar。)

from foo import bar as baz 允许 bar 是由模块 foo 导出的任何属性:bar 可以是一个子模块,或一个类,或者 foo 中定义的任何其他全局变量。

(这也是为什么 import 是一个语句而不仅仅是一个函数调用的原因之一。如果它是一个函数,你将不得不编写 import('foo.bar') 来确保 foo.barimport 被调用之前不被解释为一个表达式。)

英文:

import foo.bar as baz requires foo.bar to be a module. It's not an expression that performs attribute lookup, but a single dotted name. (Most importantly, there's no guarantee that any package exposes the modules in the package as attributes. import foo does not guaranteed that foo.bar evaluates to the module bar contained in foo.)

from foo import bar as baz lets bar be any attribute exported by the module foo: bar could be a submodule, or a class, or any other global variable defined in foo.

(This is one reason why import is a statement, and not just a function call. If it were a function, you would have to write import('foo.bar') to ensure that foo.bar is not interpreted as an expression before import is even called.)

huangapple
  • 本文由 发表于 2023年3月20日 23:06:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75791998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定