[英]In python, what is the difference between 'import foo.bar as bar' and 'from foo import bar'?
I see this convention in pyTorch and matplotlib:我在 pyTorch 和 matplotlib 中看到了这个约定:
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
Is there a reason why the whole path ( module.submodule
) is being imported as an alias instead of just the submodule?是否有理由将整个路径(
module.submodule
)作为别名而不是子模块导入? What is the difference if I import like this:如果我这样导入有什么区别:
from torch import nn
from torch import optim
from matplotlib import pyplot as plt
Edit : So for the generic case:编辑:所以对于一般情况:
import foo.bar as bar # [1]
from foo import bar # [2]
Can there exist code which refers to bar
such that it will run with [1]
and not [2]
(and vice versa)?是否存在引用
bar
的代码,以便它将使用[1]
而不是[2]
运行(反之亦然)? Ie is there functional difference between these two ways to import?即这两种导入方式之间是否存在功能差异?
Behind the scenes, all of the import statements are essentially mapped to the builtin __import__
eg:在幕后,所有的导入语句本质上都映射到内置的
__import__
例如:
import torch.nn as nn
becomes变成
nn = __import__("torch.nn", globals(), locals(), [], 0)
similarly:相似地:
from torch import nn
becomes变成
nn = __import__("torch", globals(), locals(), ["nn"], 0)
Subtly different but functionally equivalent.略有不同但功能相同。
Reference: https://docs.python.org/3/library/functions.html# import参考: https: //docs.python.org/3/library/functions.html#import
import blank as blank
lets you reference the module as that name throughout the program. import blank as blank
允许您在整个程序中将该模块作为该名称引用。
from blank import blank
imports specific methods, functions, and classes from a module. from blank import blank
从模块中导入特定的方法、函数和类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.