使用“导入模块”; 或者“从模块导入”?
我试图找到关于最好使用 import module
还是 from module import
的综合指南。 我刚刚开始使用 Python,并尝试从最佳实践开始。
基本上,我希望是否有人可以分享他们的经验,其他开发人员有哪些偏好,以及避免未来遇到任何问题的最佳方法是什么?
I've tried to find a comprehensive guide on whether it is best to use import module
or from module import
. I've just started with Python and I'm trying to start off with best practices in mind.
Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
这是我当前目录的目录结构:
import
语句会记住所有中间名称。这些名称必须合格:
from ... import ...
语句仅记住导入的名称。此名称不得被限定:
This is my directory structure of my current directory:
The
import
statement remembers all intermediate names.These names have to be qualified:
The
from ... import ...
statement remembers only the imported name.This name must not be qualified:
补充一下人们对 from x import * 的看法:除了让辨别名称的来源变得更加困难之外,这还会导致像 Pylint 这样的代码检查器无法使用。 他们会将这些名称报告为未定义的变量。
To add to what people have said about
from x import *
: besides making it more difficult to tell where names came from, this throws off code checkers like Pylint. They will report those names as undefined variables.我自己对此的回答主要取决于首先,我将使用多少个不同的模块。 如果我只打算使用一两个,我通常会使用
from
...import
因为它可以减少文件其余部分中的击键次数,但如果我要使用许多不同的模块,我更喜欢import
因为这意味着每个模块参考是自记录的。 我可以看到每个符号的来源,而无需四处寻找。通常,我更喜欢普通导入的自记录风格,只有当我必须输入模块名称的次数超过 10 到 20 次时,才会更改为 from.. import,即使只导入一个模块。
My own answer to this depends mostly on first, how many different modules I'll be using. If i'm only going to use one or two, I'll often use
from
...import
since it makes for fewer keystrokes in the rest of the file, but if I'm going to make use of many different modules, I prefer justimport
because that means that each module reference is self-documenting. I can see where each symbol comes from without having to hunt around.Usuaully I prefer the self documenting style of plain import and only change to from.. import when the number of times I have to type the module name grows above 10 to 20, even if there's only one module being imported.
有很多答案,但没有提到测试(使用
unittest
或pytest
)。tl;dr
对外部模块使用
import foo
来简化测试。困难的方法
从模块中单独导入类/函数(
from foo import bar
)会使红绿重构循环变得乏味。 例如,如果我的文件看起来像并且我的测试是
乍一看,这看起来很棒。 但是,如果我想在不同的文件中实现
Thing
类,会发生什么情况? 我的结构必须像这样改变......不幸的是,由于我使用了 from foo import bar ,我需要更新我的补丁以引用tools模块。 本质上,由于我的测试对实现了解太多,因此需要进行比预期更多的更改才能进行此重构。
更好的方法
使用
import foo
,我的测试可以忽略模块的实现方式并简单地修补整个模块。您的测试了解的实现细节越少越好。 这样,如果您想出更好的解决方案(使用类而不是函数,使用附加文件来分离想法等),则在测试中需要进行的更改就更少以适应重构。
There have been many answers, but none have mentioned testing (with
unittest
orpytest
).tl;dr
Use
import foo
for external modules to simplify testing.The Hard Way
Importing classes/functions (
from foo import bar
) individually from a module makes red-green-refactor cycles tedious. For example, if my file looks likeand my test is
At first glance, this seems great. But what happens if I want to implement
Thing
class in a different file? My structure would have to change like this...Unfortunately, since I used
from foo import bar
, I need to update my patch to reference thetools
module. Essentially, since my test knows too much about implementation, much more than expected needs to be changed to do this refactor.The Better Approach
Using
import foo
, my tests can ignore how the module is implemented and simply patch the whole module.The less implementation details your tests know, the better. That way, if you come up with a better solution (use classes instead of functions, use additional files to separate ideas, etc.), less needs to be changed in your tests to accommodate the refactor.
我发现的一个显着差异令人惊讶没有人谈论过,那就是使用简单的导入你可以访问
私有变量
和来自导入模块的私有函数
,这是 from-import 语句不可能实现的。图片中的代码:
setting.py
plain_importer.py
from_importer.py
One of the significant difference I found out which surprisingly no-one has talked about is that using plain import you can access
private variable
andprivate functions
from the imported module, which isn't possible with from-import statement.Code in image:
setting.py
plain_importer.py
from_importer.py
正如 Jan Wrobel 提到的,不同导入的一个方面是导入的披露方式。
模块mymath
mymath的使用:
如果我导入
gcd
只是为了内部使用,而不是透露给mymath
的用户>,这可能会很不方便。 我经常遇到这种情况,在大多数情况下我想“保持我的模块干净”。除了 Jan Wrobel 提出通过使用
import math
来模糊这一点的建议之外,我已经开始通过使用前导下划线来隐藏导入以防止公开:在较大的项目中这种“最佳实践”使我能够准确控制向后续进口披露的内容以及不披露的内容。 这使我的模块保持干净,并在一定规模的项目中得到回报。
As Jan Wrobel mentions, one aspect of the different imports is in which way the imports are disclosed.
Module mymath
Use of mymath:
If I imported
gcd
only for internal use, not to disclose it to users ofmymath
, this can be inconvenient. I have this pretty often, and in most cases I want to "keep my modules clean".Apart from the proposal of Jan Wrobel to obscure this a bit more by using
import math
instead, I have started to hide imports from disclosure by using a leading underscore:In larger projects this "best practice" allows my to exactly control what is disclosed to subsequent imports and what isn't. This keeps my modules clean and pays back at a certain size of project.
因为很多人都在这里回答,但我只是尽力而为:)
module
导入哪个项目时,import module
是最好的选择。 这样当问题出现时可能很难调试,因为您不知道哪个项目有问题。
form module import
是最好的选择,并且还有助于根据您的需要使用导入特定项目进行更多控制。 使用这种方式调试可能会很容易,因为您知道导入了哪个项目。since many people answered here but i am just trying my best :)
import module
is best when you don't know which item you have to import frommodule
. In this way it may be difficult to debug when problem raises becauseyou don't know which item have problem.
form module import <foo>
is best when you know which item you require to import and also helpful in more controlling using importing specific item according to your need. Using this way debugging may be easy because you know which item you imported.导入模块 - 您不需要额外的努力来从模块中获取其他内容。 它有一些缺点,例如冗余输入
模块导入自 - 更少的输入和更多的控制可以访问模块的哪些项目。要使用模块中的新项目,您必须更新导入语句。
Import Module - You don't need additional efforts to fetch another thing from module. It has disadvantages such as redundant typing
Module Import From - Less typing &More control over which items of a module can be accessed.To use a new item from the module you have to update your import statement.
有一些内置模块主要包含裸函数(base64,数学,os, shutil ,sys,time, ...) 绑定这些裸函数绝对是一个好习惯 到某个命名空间,从而提高代码的可读性。 考虑一下在没有命名空间的情况下理解这些函数的含义
比它们绑定到某个模块时
要困难得多:有时您甚至需要命名空间来避免不同模块之间的冲突(json.load 与 pickle.load)
On the other hand there are some modules that contain mostly classes (configparser, datetime, tempfile, zipfile, ...) and many of them make their class names self-explanatory enough:
因此,在代码中使用这些类和附加模块命名空间是否会添加一些新信息或只是延长代码可能存在争议。
There are some builtin modules that contain mostly bare functions (base64, math, os, shutil, sys, time, ...) and it is definitely a good practice to have these bare functions bound to some namespace and thus improve the readability of your code. Consider how more difficult is to understand the meaning of these functions without their namespace:
than when they are bound to some module:
Sometimes you even need the namespace to avoid conflicts between different modules (json.load vs. pickle.load)
On the other hand there are some modules that contain mostly classes (configparser, datetime, tempfile, zipfile, ...) and many of them make their class names self-explanatory enough:
so there can be a debate whether using these classes with the additional module namespace in your code adds some new information or just lengthens the code.
我正在回答类似的问题帖子,但发布者在我发帖之前将其删除。 这是一个例子来说明差异。
Python 库可能有一个或多个文件(模块)。 例如,
我们
可以在任何基于设计要求的文件中定义 python 函数或类。
让我们
mylibrary1
下的__init__.py
中定义func1()
,并module2 中定义
在foo()
。 pymylibrary2
下。我们可以使用以下方法之一访问
func1()
或
or
or
我们可以使用以下方法之一访问
foo()
:or
or
or
or
I was answering a similar question post but the poster deleted it before i could post. Here is one example to illustrate the differences.
Python libraries may have one or more files (modules). For exmaples,
or
We can define python functions or classes inside any of the files based design requirements.
Let's define
func1()
in__init__.py
undermylibrary1
, andfoo()
inmodule2.py
undermylibrary2
.We can access
func1()
using one of these methodsor
or
or
We can use one of these methods to access
foo()
:or
or
or
or
简单来说,这都是为了程序员的方便。 在核心级别,他们只需导入模块的所有功能。
导入模块
:当您使用导入模块
时,要使用该模块的方法,您必须编写module.method(). 每次使用任何方法或属性时,都必须引用该模块。
from module import all
:当您使用from module import all
而不是使用此模块的方法时,您只需编写method( )
而不引用模块。In simple words, this is all about programmer convenience. At the core level, they simply import all functionality of the module.
import module
: When you useimport module
then to use methods of this module you have to writemodule.method()
. Every time you use any method or property then you have to refer to the module.from module import all
: When you usefrom module import all
than to use methods of this module you just have to writemethod()
without referring to the module.@ahfx 已经提到了这些导入的一个关键方面,即加载模块过程的内部结构。 如果您的系统需要使用循环导入(例如您想在一些流行的 http 框架中使用依赖注入),则会弹出此消息。 在这种情况下,
from {module} import {function}
对加载过程如何进行的要求显得更加激进。 让我们举个例子:importing
run via
在
m2.py
(A,B,C,D) 中的所有导入可能性中,from {module} import {function}
是唯一真正使加载过程崩溃的,导致臭名昭著的(CPython 3.10.6)虽然我不能说为什么会发生这种情况,但似乎是
from ... import 。 ..
语句对相关模块已经处于初始化过程中的“程度”提出了更严格的要求。There is a crucial aspect of these imports that @ahfx already mentioned, namely the internals of the process of loading modules. This pops up if your system needs to use circular imports (e.g. you want to make use of dependency injection in some popular http frameworks). In such cases the
from {module} import {function}
appears much more aggressive with its requirements on how the loading process proceeds. Let us take the example:importing
run via
Of all the import possibilities in
m2.py
(A,B,C,D), thefrom {module} import {function}
is the only one that actually crashes the load process, leading to the infamous (CPython 3.10.6)While I cannot say why this happens, it appears that the
from ... import ...
statement puts a more stringent requirement on "how far" the module in question is already in its initialization process.import module
和from module import foo
之间的区别主要是主观的。 选择您最喜欢的一个并在使用过程中保持一致。 以下几点可以帮助您做出决定。导入模块
import
语句的维护。 不需要添加任何额外的导入即可开始使用模块中的另一个项目module.foo
可能会很乏味且多余(可以通过使用import module as mo
然后输入mo.foo
来最大程度地减少乏味。代码>)from module import foo
foo
减少输入import
语句foo
的上下文。 例如,与math.ceil()
相比,ceil()
的作用不太清楚两种方法都可以接受,但不要使用 <代码>从模块导入*。
对于任何合理的大型代码集,如果您
import *
,您可能会将其固定到模块中,无法删除。 这是因为很难确定代码中使用的哪些项目来自“模块”,因此很容易达到您认为不再使用import
但实际上是这样的地步。很难确定。The difference between
import module
andfrom module import foo
is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.import module
import
statements. Don't need to add any additional imports to start using another item from the modulemodule.foo
in your code can be tedious and redundant (tedium can be minimized by usingimport module as mo
then typingmo.foo
)from module import foo
foo
import
statementfoo
. For example, it's less clear whatceil()
does compared tomath.ceil()
Either method is acceptable, but don't use
from module import *
.For any reasonable large set of code, if you
import *
you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use theimport
any more but it's extremely difficult to be sure.这里还有一个未提及的细节,与写入模块有关。 当然这可能不是很常见,但我时不时需要它。
由于引用和名称绑定在 Python 中的工作方式,如果您想从模块外部更新模块中的某些符号(例如 foo.bar),并且让其他导入代码“看到”该更改,则必须导入 foo某种方式。 例如:
module foo:
module a:
module b:
但是,如果导入符号名称而不是模块名称,则这将不起作用。
例如,如果我在模块 a 中执行此操作:
a
之外的任何代码都不会将bar
视为“橙子”,因为我的bar
设置仅仅是影响了模块a
内的名称“bar”,它没有“到达”foo
模块对象并更新其bar
。There's another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I've needed it from time to time.
Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importing code "see" that change, you have to import foo a certain way. For example:
module foo:
module a:
module b:
However, if you import symbol names instead of module names, this will not work.
For example, if I do this in module a:
No code outside of
a
will seebar
as "oranges" because my setting ofbar
merely affected the name "bar" inside modulea
, it did not "reach into" thefoo
module object and update itsbar
.尽管很多人已经解释了
import
与import from
,但我想尝试更多地解释一下幕后发生的事情,以及它更改的所有地方。import foo
:导入
foo
,并在当前命名空间中创建对该模块的引用。 然后,您需要定义完整的模块路径以从模块内部访问特定属性或方法。例如
foo.bar
但不是bar
from foo import bar
:导入
foo
,并创建对所有成员的引用列出(栏
)。 不设置变量foo
。例如
bar
但不是baz
或foo.baz
from foo import *
:导入
foo
,并创建对该模块在当前命名空间中定义的所有公共对象的引用(如果__all__
存在,则在__all__
中列出所有内容,否则不以开头的所有内容>_
)。 不设置变量foo
。例如
bar
和baz
,但不是_qux
或foo._qux
。现在让我们看看何时
import XY
:检查名称为
os
和os.path
的sys.modules
:检查
globals()
和locals()
命名空间字典以及os
和os.path
:从上面的例子中我们发现只有
os
被插入到本地和全局命名空间中。所以,我们应该能够使用:
但不能使用
path
。一旦您从 locals() 命名空间中删除了
os
,您将无法访问os
以及os.path
,即使它们存在于 sys.modules 中:现在我们来谈谈
import from
:from
:用
os
检查sys.modules
并os.path
:我们发现在
sys.modules
中我们发现与之前使用import name
相同的内容,好的,让我们检查一下它是如何实现的看起来像在
locals()
和globals()
命名空间字典中:您可以使用名称
path
访问,而不是通过os.path< /code>:
让我们从
locals()
中删除“路径”:最后一个使用别名的示例:
并且没有定义路径:
Even though many people already explained about
import
vsimport from
, I want to try to explain a bit more about what happens under the hood, and where all the places it changes are.import foo
:Imports
foo
, and creates a reference to that module in the current namespace. Then you need to define completed module path to access a particular attribute or method from inside the module.E.g.
foo.bar
but notbar
from foo import bar
:Imports
foo
, and creates references to all the members listed (bar
). Does not set the variablefoo
.E.g.
bar
but notbaz
orfoo.baz
from foo import *
:Imports
foo
, and creates references to all public objects defined by that module in the current namespace (everything listed in__all__
if__all__
exists, otherwise everything that doesn't start with_
). Does not set the variablefoo
.E.g.
bar
andbaz
but not_qux
orfoo._qux
.Now let’s see when we do
import X.Y
:Check
sys.modules
with nameos
andos.path
:Check
globals()
andlocals()
namespace dicts withos
andos.path
:From the above example we found that only
os
is inserted in the local and global namespace.So, we should be able to use:
But not
path
.Once you delete the
os
from locals() namespace, you won't be able to accessos
as well asos.path
even though they exist in sys.modules:Now let's talk about
import from
:from
:Check
sys.modules
withos
andos.path
:We found that in
sys.modules
we found as same as we did before by usingimport name
OK, let's check how it looks like in
locals()
andglobals()
namespace dicts:You can access by using name
path
not byos.path
:Let's delete 'path' from
locals()
:One final example using an alias:
And no path defined:
这两种方式都受到支持是有原因的:有时一种方式比另一种方式更合适。
导入模块
:当您使用模块中的许多位时,这很好。 缺点是您需要使用模块名称来限定每个引用。from module import ...
:很高兴导入的项目可以直接使用,无需模块名称前缀。 缺点是你必须列出你使用的每一个东西,并且在代码中不清楚东西来自哪里。使用哪个取决于哪个使代码清晰易读,并且与个人喜好有很大关系。 我通常倾向于
导入模块
,因为在代码中,对象或函数的来源非常清楚。 当我在代码中大量使用某些对象/函数时,我会使用from module import ...
。Both ways are supported for a reason: there are times when one is more appropriate than the other.
import module
: nice when you are using many bits from the module. drawback is that you'll need to qualify each reference with the module name.from module import ...
: nice that imported items are usable directly without module name prefix. The drawback is that you must list each thing you use, and that it's not clear in code where something came from.Which to use depends on which makes the code clear and readable, and has more than a little to do with personal preference. I lean toward
import module
generally because in the code it's very clear where an object or function came from. I usefrom module import ...
when I'm using some object/function a lot in the code.我个人总是使用
并访问所有内容,等等
。原因是,同时您的调用很短,并且您清楚地定义了每个例程的模块名称空间,如果您必须搜索给定的使用情况,这非常有用源中的模块。
不用说,不要使用 import *,因为它会污染你的命名空间,并且它不会告诉你给定的函数来自哪里(来自哪个模块)
当然,如果两个模块名称相同,你可能会遇到麻烦不同的模块位于两个不同的包中,就像
在这种情况下,当然你会遇到麻烦,但是强烈暗示你的包布局有缺陷,你必须重新考虑它。
I personally always use
and then access everything as
etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if you have to search for usage of a given module in your source.
Needless to say, do not use the import *, because it pollutes your namespace and it does not tell you where a given function comes from (from which module)
Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like
in this case, of course you run into troubles, but then there's a strong hint that your package layout is flawed, and you have to rethink it.
当您将使用模块中的许多功能时这是最好的选择。
当您只需要
function
时,如果您想避免模块中的所有函数和类型污染全局命名空间,这是最好的选择。Is best when you will use many functions from the module.
Is best when you want to avoid polluting the global namespace with all the functions and types from a module when you only need
function
.我刚刚发现这两种方法之间的一个更微妙的区别。
如果模块
foo
使用以下导入:那么模块
bar
可能会错误地使用count
,就好像它是在foo
,不在itertools
中:如果
foo
使用:错误仍然有可能,但不太可能发生。
bar
need to:这给我带来了一些麻烦。 我有一个模块错误地从一个没有定义它的模块导入了一个异常,只是从其他模块导入了它(使用
from module import SomeException
)。 当不再需要并删除导入时,有问题的模块就被破坏了。I've just discovered one more subtle difference between these two methods.
If module
foo
uses a following import:Then module
bar
can by mistake usecount
as though it was defined infoo
, not initertools
:If
foo
uses:the mistake is still possible, but less likely to be made.
bar
needs to:This caused some troubles to me. I had a module that by mistake imported an exception from a module that did not define it, only imported it from other module (using
from module import SomeException
). When the import was no longer needed and removed, the offending module was broken.这里还有一个没有提到的区别。 这是从 http://docs.python.org/2/tutorial/modules 逐字复制的。请
注意,使用时
该项目可以是包的子模块(或子包),也可以是包中定义的其他名称,例如函数、类或变量。 import语句首先测试包中是否定义了该项; 如果不是,它假设它是一个模块并尝试加载它。 如果找不到它,则会引发 ImportError 异常。
相反,当使用语法时,
除了最后一项之外的每个项目都必须是一个包; 最后一项可以是模块或包,但不能是前一项中定义的类、函数或变量。
Here is another difference not mentioned. This is copied verbatim from http://docs.python.org/2/tutorial/modules.html
Note that when using
the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.
Contrarily, when using syntax like
each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.
由于我也是初学者,所以我将尝试以简单的方式解释这一点:
在 Python 中,我们有三种类型的
import
语句,它们是:1. 通用导入:
这种类型的导入是我个人最喜欢的,这种导入技术的唯一缺点是,如果您需要使用任何模块的功能,则必须使用以下语法:
of当然,它会增加打字工作量,但作为初学者,它将帮助您跟踪与其相关的模块和功能(良好的文本编辑器将显着减少打字工作量,建议使用)。
使用此导入语句可以进一步减少输入工作量:
现在,您可以使用
m 而不是使用
.math.sqrt()
.sqrt()2. 函数导入:
如果您的代码只需要访问模块中的单个或几个函数,则这种类型的导入最适合,但要使用模块中的任何新项,您必须更新导入语句。 em>
3。 通用导入:
虽然它显着减少了打字工作,但不推荐,因为它会用模块中的各种函数填充您的代码,并且它们的名称可能与用户定义函数的名称冲突。
示例:
如果您有一个自己命名的 sqrt 函数并且导入了 math,则您的函数是安全的:有您的 sqrt,也有 math.sqrt。 但是,如果您执行 from math import * 操作,则会遇到一个问题:即两个不同的函数具有完全相同的名称。 来源:Codecademy
Since I am also a beginner, I will be trying to explain this in a simple way:
In Python, we have three types of
import
statements which are:1. Generic imports:
this type of import is my personal favorite, the only downside to this import technique is that if you need use any module's function you must use the following syntax:
of course, it increases the typing effort but as a beginner, it will help you to keep track of module and function associated with it, (a good text editor will reduce the typing effort significantly and is recommended).
Typing effort can be further reduced by using this import statement:
now, instead of using
math.sqrt()
you can usem.sqrt()
.2. Function imports:
this type of import is best suited if your code only needs to access single or few functions from the module, but for using any new item from the module you have to update import statement.
3. Universal imports:
Although it reduces typing effort significantly but is not recommended because it will fill your code with various functions from the module and their name could conflict with the name of user-defined functions.
example:
If you have a function of your very own named sqrt and you import math, your function is safe: there is your sqrt and there is math.sqrt. If you do from math import *, however, you have a problem: namely, two different functions with the exact same name. Source: Codecademy
我想补充一下。 如果遇到循环导入,了解 Python 如何将导入的模块作为属性处理会很有用。
我有以下结构:
从 main.py 我将使用不同的导入方法导入其他模块
main.py:
dis.dis 显示差异(注意模块名称,abcd):
最后它们看起来相同(STORE_NAME 的结果是每个示例),但如果您需要考虑以下四个循环导入,则值得注意:
example1
这有效
example2
无骰子
example3
不同
类似的问题...但显然 from x import y 与 import import xy as y example4
这 一个也有效
I would like to add to this. It can be useful to understand how Python handles imported modules as attributes if you run into circular imports.
I have the following structure:
From main.py I will import the other modules using differnt import methods
main.py:
dis.dis shows the difference (note module names, a b c d):
In the end they look the same (STORE_NAME is result in each example), but this is worth noting if you need to consider the following four circular imports:
example1
This works
example2
No dice
example3
Similar issue... but clearly from x import y is not the same as import import x.y as y
example4
This one also works
使用
import
时,令牌必须是模块(包含 Python 命令的文件)或包(sys.path
中包含文件__init__.py 的文件夹)
。)当有子包时:
文件夹(包)或文件(模块)的要求相同,但文件夹或文件必须位于
package2
内,而package2
必须位于内package1
,并且package1
和package2
都必须包含__init__.py
文件。 https://docs.python.org/2/tutorial/modules.html使用
from
风格的导入:包或模块进入包含
import
语句的文件的命名空间作为module
(或package
)而不是package1.package2.module
。 您始终可以绑定到更方便的名称:只有
from
样式的导入允许您命名特定的函数或变量:允许,但
不允许。
With
import
, the token must be a module (a file containing Python commands) or a package (a folder in thesys.path
containing a file__init__.py
.)When there are subpackages:
the requirements for folder (package) or file (module) are the same, but the folder or file must be inside
package2
which must be insidepackage1
, and bothpackage1
andpackage2
must contain__init__.py
files. https://docs.python.org/2/tutorial/modules.htmlWith the
from
style of import:the package or module enters the namespace of the file containing the
import
statement asmodule
(orpackage
) instead ofpackage1.package2.module
. You can always bind to a more convenient name:Only the
from
style of import permits you to name a particular function or variable:is allowed, but
is not allowed.