使用'import module'还是'from module' ?

时间:2023-01-23 22:01:04

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.

我试图找到一个全面的指南,关于使用导入模块还是模块导入是最好的?我刚开始使用Python,我想从最佳实践开始。

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?

基本上,我希望如果有人能分享他们的经验,其他开发人员有什么偏好,以及在未来避免任何问题的最好方法是什么?

13 个解决方案

#1


308  

The difference between import module and from 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.

导入模块和模块导入foo之间的区别主要是主观的。选择你最喜欢的,并且在你的使用中保持一致。这里有几点可以帮助你做出决定。

import module

导入模块

  • Pros:
    • Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module
    • 减少对导入语句的维护。不需要添加任何额外的导入来开始使用模块中的其他项。
  • 优点:较少维护您的导入语句。不需要添加任何额外的导入来开始使用模块中的其他项。
  • Cons:
    • Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)
    • 输入模块。在您的代码中,foo是冗长乏味的,冗余的(可以通过使用import模块来最小化,然后输入mo.foo)。
  • 缺点:输入模块。在您的代码中,foo是冗长乏味的,冗余的(可以通过使用import模块来最小化,然后输入mo.foo)。

from module import foo

从模块导入foo

  • Pros:
    • Less typing to use foo
    • 使用foo时输入更少
    • More control over which items of a module can be accessed
    • 对可以访问模块项的更多控制
  • 优点:更少的输入来使用foo,更多的控制可以访问模块的项目
  • Cons:
    • To use a new item from the module you have to update your import statement
    • 要使用模块中的新项,必须更新导入语句
    • You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()
    • 你失去了关于foo的上下文。例如,与math.ceil()相比,ceil()做了什么就不太清楚了
  • 缺点:要使用模块中的新项,必须更新导入语句,否则会丢失有关foo的上下文。例如,与math.ceil()相比,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 the import any more but it's extremely difficult to be sure.

对于任何合理的大型代码集,如果您导入*,您可能会将其绑定到模块中,无法删除。这是因为很难确定在代码中使用的项目来自“module”,这使得您很容易就会认为不再使用导入,但是很难确定。

#2


62  

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:

由于引用和名称绑定在Python中的工作方式,如果您希望更新模块中的某些符号,请使用foo。bar,从模块外,还有其他导入代码"see"那个变化,你必须以某种方式导入foo。例如:

module foo:

模块foo:

bar = "apples"

module a:

模块一:

import foo
foo.bar = "oranges"   # update bar inside foo module object

module b:

模块2:

import foo           
print foo.bar        # if executed after a's "foo.bar" assignment, will print "oranges"

However, if you import symbol names instead of module names, this will not work.

但是,如果您导入的是符号名称而不是模块名称,这将不起作用。

For example, if I do this in module a:

例如,如果我在模块a中这样做:

from foo import bar
bar = "oranges"

No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its "bar".

a之外没有代码会将bar视为“桔子”,因为我的bar设置仅仅影响了模块a中的名称“bar”,它没有“触及”foo模块对象并更新它的“bar”。

#3


38  

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 use from module import ... when I'm using some object/function a lot in the code.

使用哪一种取决于哪一种代码更清晰、更可读,这与个人偏好有很大关系。我倾向于导入模块,因为在代码中很清楚对象或函数来自哪里。我从模块导入…当我在代码中大量使用对象/函数时。

#4


29  

Even though many people already explained about import vs import from, I want to try to explain a bit more about what happens under the hood, and where all the places it changes are.

尽管许多人已经解释了导入和导入,但我还是想尝试解释一下在hood的底层发生了什么,以及它所改变的地方在哪里。


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.

导入foo,并在当前名称空间中创建对该模块的引用。然后需要定义完整的模块路径,以便从模块内部访问特定的属性或方法。

E.g. foo.bar but not bar

例如foo。酒吧但不是酒吧

from foo import bar:

Imports foo, and creates references to all the members listed (bar). Does not set the variable foo.

导入foo,并创建对列出的所有成员的引用(bar)。不设置变量foo。

E.g. bar but not baz or foo.baz

例如bar,而不是baz或foo.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 variable foo.

导入foo,并创建对当前命名空间中该模块定义的所有公共对象的引用(如果__all__存在,则在__all__中列出的所有内容,否则所有不以_开头的内容)。不设置变量foo。

E.g. bar and baz but not _qux or foo._qux.

例如bar和baz,而不是_qux或foo._qux。


Now let’s see when we do import X.Y:

现在我们来看看导入x。y:

>>> import sys
>>> import os.path

Check sys.modules with name os and os.path:

检查系统。名称为os和os.path的模块:

>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>

Check globals() and locals() namespace dicts with os and os.path:

使用os和os.path检查globals()和local()名称空间规则:

 >>> globals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> locals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> globals()['os.path']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'os.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:

从上面的示例中,我们发现只有os被插入到本地和全局名称空间中。因此,我们应该能够使用:

 >>> os
 <module 'os' from
  '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
 >>> os.path
 <module 'posixpath' from
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
 >>>

But not path.

但不是路径。

>>> path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>

Once you delete the os from locals() namespace, you won't be able to access os as well as os.path even though they exist in sys.modules:

一旦您从local()名称空间中删除操作系统,您将无法访问操作系统和操作系统。路径,即使它们存在于系统中。

>>> del locals()['os']
>>> os
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> os.path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>

Now let's talk about import from:

from:

>>> import sys
>>> from os import path

Check sys.modules with os and os.path:

>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>

We found that in sys.modules we found as same as we did before by using import name

我们在sys中发现。我们发现的模块和以前使用导入名称时一样。

OK, let's check how it looks like in locals() and globals() namespace dicts:

好的,让我们检查一下它在local()和globals()名称空间中的情况:

>>> globals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> locals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['os']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'os'
>>>

You can access by using name path not by os.path:

您可以使用名称路径访问,而不是使用os.path:

>>> path
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> os.path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>

Let's delete 'path' from locals():

让我们从local()中删除“path”:

>>> del locals()['path']
>>> path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>

One final example using an alias:

最后一个使用别名的例子:

>>> from os import path as HELL_BOY
>>> locals()['HELL_BOY']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['HELL_BOY']
<module 'posixpath' from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>

And no path defined:

没有定义路径:

>>> globals()['path']
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: 'path'
>>>

#5


28  

I personally always use

我总是使用

from package.subpackage.subsubpackage import module

and then access everything as

然后访问所有的as

module.function
module.modulevar

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)

不用说,不要使用import *,因为它会污染您的命名空间,而且它不会告诉您给定的函数来自何处(来自哪个模块)

Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like

当然,如果在两个不同的包中有两个不同模块的相同模块名称,就会遇到麻烦。

from package1.subpackage import module
from package2.subpackage import module

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.

在这种情况下,当然您遇到了麻烦,但是有一个强烈的提示,您的包布局是有缺陷的,您必须重新考虑它。

#6


12  

import module

Is best when you will use many functions from the module.

当您将使用模块中的许多函数时,它是最佳的。

from module import function

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.

当您希望避免在只需要函数时使用模块中的所有函数和类型污染全局命名空间时,它是最佳的。

#7


7  

Here is another difference not mentioned. This is copied verbatim from http://docs.python.org/2/tutorial/modules.html

这里还有另一个未提及的区别。这是从http://docs.python.org/2/tutorial/modules.html逐字复制的

Note that when using

注意,当使用

from package import item

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

相反,在使用语法时

import item.subitem.subsubitem

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.

除最后一项外,每一项都必须是一个包裹;最后一项可以是模块或包,但不能是在前一项中定义的类、函数或变量。

#8


4  

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.

再加上人们在x import中说过的内容*:除了让人更难知道名称来自哪里之外,这还会引发像Pylint这样的代码检查。它们将这些名称作为未定义的变量进行报告。

#9


4  

I've just discovered one more subtle difference between these two methods.

我刚刚发现了这两种方法之间更微妙的区别。

If module foo uses a following import:

如果模块foo使用以下导入:

from itertools import count

Then module bar can by mistake use count as though it was defined in foo, not in itertools:

然后模块条可以错误地使用count,就好像它是在foo中定义的,而不是在itertools中:

import foo
foo.count()

If foo uses:

如果foo用途:

import itertools

the mistake is still possible, but less likely to be made. bar needs to:

这个错误仍然是可能的,但不太可能发生。酒吧需要:

import foo
foo.itertools.count()

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.

这给我带来了一些麻烦。我有一个模块,错误地从没有定义它的模块导入了一个异常,只从其他模块导入它(使用模块导入SomeException)。当导入不再需要并删除时,这个问题模块就被破坏了。

#10


3  

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 just import because that means that each module reference is self-documenting. I can see where each symbol comes from without having to hunt around.

我自己的答案主要取决于首先,我将使用多少不同的模块。如果我只使用一到两个,我会经常使用from…因为它在文件的其余部分减少了击键,但是如果我要使用许多不同的模块,我更喜欢导入,因为这意味着每个模块引用都是自文档化的。我可以看到每个符号的来源,而不用四处搜寻。

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.

通常我更喜欢用自己的方式来记录简单的进口,而只是从……当我必须键入模块名的次数在10到20之间时,即使只有一个模块被导入,也需要导入。

#11


2  

import package
import module

With import, the token must be a module (a file containing Python commands) or a package (a folder in the sys.path containing a file __init__.py.)

对于导入,标记必须是模块(包含Python命令的文件)或包(sys中的文件夹)。包含文件__init__.py的路径。

When there are subpackages:

当有子包:

import package1.package2.package
import package1.package2.module

the requirements for folder (package) or file (module) are the same, but the folder or file must be inside package2 which must be inside package1, and both package1 and package2 must contain __init__.py files. https://docs.python.org/2/tutorial/modules.html

文件夹(包)或文件(模块)的要求是相同的,但是文件夹或文件必须在package2中,而package1和package2都必须包含__init__。py文件。https://docs.python.org/2/tutorial/modules.html

With the from style of import:

进口风格:

from package1.package2 import package
from package1.package2 import module

the package or module enters the namespace of the file containing the import statement as module (or package) instead of package1.package2.module. You can always bind to a more convenient name:

包或模块将包含导入语句的文件的名称空间输入为模块(或包),而不是package1.package2.module。你可以用一个更方便的名字:

a = big_package_name.subpackage.even_longer_subpackage_name.function

Only the from style of import permits you to name a particular function or variable:

只有从输入样式允许您命名一个特定的函数或变量:

from package3.module import some_function

is allowed, but

是可以的,但

import package3.module.some_function 

is not allowed.

是不允许的。

#12


0  

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.

模块导入-较少的键入和更多的控制项的模块可以被访问。要使用模块中的新项,必须更新导入语句。

#13


0  

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:

由于我也是一个初学者,我将尝试用简单的方式来解释这一点:在Python中,我们有三种类型的导入语句:

1. Generic imports:

1。一般进口:

import math

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:

这种类型的导入是我个人最喜欢的,这种导入技术唯一的缺点是,如果您需要使用任何模块的函数,您必须使用以下语法:

math.sqrt(4)

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:

使用这个导入语句可以进一步减少输入工作:

import math as m

now, instead of using math.sqrt() you can use m.sqrt().

现在,您可以使用m.s rrt()而不是math.sqrt()。

2. Function imports:

2。功能导入:

from math import sqrt

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.

如果您的代码只需要从模块访问单个或很少的函数,那么这种类型的导入是最合适的,但是对于从模块中使用任何新项,您必须更新import语句。

3. Universal imports:

3所示。普遍的进口:

from math import 

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

#1


308  

The difference between import module and from 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.

导入模块和模块导入foo之间的区别主要是主观的。选择你最喜欢的,并且在你的使用中保持一致。这里有几点可以帮助你做出决定。

import module

导入模块

  • Pros:
    • Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module
    • 减少对导入语句的维护。不需要添加任何额外的导入来开始使用模块中的其他项。
  • 优点:较少维护您的导入语句。不需要添加任何额外的导入来开始使用模块中的其他项。
  • Cons:
    • Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)
    • 输入模块。在您的代码中,foo是冗长乏味的,冗余的(可以通过使用import模块来最小化,然后输入mo.foo)。
  • 缺点:输入模块。在您的代码中,foo是冗长乏味的,冗余的(可以通过使用import模块来最小化,然后输入mo.foo)。

from module import foo

从模块导入foo

  • Pros:
    • Less typing to use foo
    • 使用foo时输入更少
    • More control over which items of a module can be accessed
    • 对可以访问模块项的更多控制
  • 优点:更少的输入来使用foo,更多的控制可以访问模块的项目
  • Cons:
    • To use a new item from the module you have to update your import statement
    • 要使用模块中的新项,必须更新导入语句
    • You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()
    • 你失去了关于foo的上下文。例如,与math.ceil()相比,ceil()做了什么就不太清楚了
  • 缺点:要使用模块中的新项,必须更新导入语句,否则会丢失有关foo的上下文。例如,与math.ceil()相比,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 the import any more but it's extremely difficult to be sure.

对于任何合理的大型代码集,如果您导入*,您可能会将其绑定到模块中,无法删除。这是因为很难确定在代码中使用的项目来自“module”,这使得您很容易就会认为不再使用导入,但是很难确定。

#2


62  

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:

由于引用和名称绑定在Python中的工作方式,如果您希望更新模块中的某些符号,请使用foo。bar,从模块外,还有其他导入代码"see"那个变化,你必须以某种方式导入foo。例如:

module foo:

模块foo:

bar = "apples"

module a:

模块一:

import foo
foo.bar = "oranges"   # update bar inside foo module object

module b:

模块2:

import foo           
print foo.bar        # if executed after a's "foo.bar" assignment, will print "oranges"

However, if you import symbol names instead of module names, this will not work.

但是,如果您导入的是符号名称而不是模块名称,这将不起作用。

For example, if I do this in module a:

例如,如果我在模块a中这样做:

from foo import bar
bar = "oranges"

No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its "bar".

a之外没有代码会将bar视为“桔子”,因为我的bar设置仅仅影响了模块a中的名称“bar”,它没有“触及”foo模块对象并更新它的“bar”。

#3


38  

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 use from module import ... when I'm using some object/function a lot in the code.

使用哪一种取决于哪一种代码更清晰、更可读,这与个人偏好有很大关系。我倾向于导入模块,因为在代码中很清楚对象或函数来自哪里。我从模块导入…当我在代码中大量使用对象/函数时。

#4


29  

Even though many people already explained about import vs import from, I want to try to explain a bit more about what happens under the hood, and where all the places it changes are.

尽管许多人已经解释了导入和导入,但我还是想尝试解释一下在hood的底层发生了什么,以及它所改变的地方在哪里。


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.

导入foo,并在当前名称空间中创建对该模块的引用。然后需要定义完整的模块路径,以便从模块内部访问特定的属性或方法。

E.g. foo.bar but not bar

例如foo。酒吧但不是酒吧

from foo import bar:

Imports foo, and creates references to all the members listed (bar). Does not set the variable foo.

导入foo,并创建对列出的所有成员的引用(bar)。不设置变量foo。

E.g. bar but not baz or foo.baz

例如bar,而不是baz或foo.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 variable foo.

导入foo,并创建对当前命名空间中该模块定义的所有公共对象的引用(如果__all__存在,则在__all__中列出的所有内容,否则所有不以_开头的内容)。不设置变量foo。

E.g. bar and baz but not _qux or foo._qux.

例如bar和baz,而不是_qux或foo._qux。


Now let’s see when we do import X.Y:

现在我们来看看导入x。y:

>>> import sys
>>> import os.path

Check sys.modules with name os and os.path:

检查系统。名称为os和os.path的模块:

>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>

Check globals() and locals() namespace dicts with os and os.path:

使用os和os.path检查globals()和local()名称空间规则:

 >>> globals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> locals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> globals()['os.path']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'os.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:

从上面的示例中,我们发现只有os被插入到本地和全局名称空间中。因此,我们应该能够使用:

 >>> os
 <module 'os' from
  '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
 >>> os.path
 <module 'posixpath' from
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
 >>>

But not path.

但不是路径。

>>> path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>

Once you delete the os from locals() namespace, you won't be able to access os as well as os.path even though they exist in sys.modules:

一旦您从local()名称空间中删除操作系统,您将无法访问操作系统和操作系统。路径,即使它们存在于系统中。

>>> del locals()['os']
>>> os
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> os.path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>

Now let's talk about import from:

from:

>>> import sys
>>> from os import path

Check sys.modules with os and os.path:

>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>

We found that in sys.modules we found as same as we did before by using import name

我们在sys中发现。我们发现的模块和以前使用导入名称时一样。

OK, let's check how it looks like in locals() and globals() namespace dicts:

好的,让我们检查一下它在local()和globals()名称空间中的情况:

>>> globals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> locals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['os']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'os'
>>>

You can access by using name path not by os.path:

您可以使用名称路径访问,而不是使用os.path:

>>> path
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> os.path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>

Let's delete 'path' from locals():

让我们从local()中删除“path”:

>>> del locals()['path']
>>> path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>

One final example using an alias:

最后一个使用别名的例子:

>>> from os import path as HELL_BOY
>>> locals()['HELL_BOY']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['HELL_BOY']
<module 'posixpath' from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>

And no path defined:

没有定义路径:

>>> globals()['path']
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: 'path'
>>>

#5


28  

I personally always use

我总是使用

from package.subpackage.subsubpackage import module

and then access everything as

然后访问所有的as

module.function
module.modulevar

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)

不用说,不要使用import *,因为它会污染您的命名空间,而且它不会告诉您给定的函数来自何处(来自哪个模块)

Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like

当然,如果在两个不同的包中有两个不同模块的相同模块名称,就会遇到麻烦。

from package1.subpackage import module
from package2.subpackage import module

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.

在这种情况下,当然您遇到了麻烦,但是有一个强烈的提示,您的包布局是有缺陷的,您必须重新考虑它。

#6


12  

import module

Is best when you will use many functions from the module.

当您将使用模块中的许多函数时,它是最佳的。

from module import function

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.

当您希望避免在只需要函数时使用模块中的所有函数和类型污染全局命名空间时,它是最佳的。

#7


7  

Here is another difference not mentioned. This is copied verbatim from http://docs.python.org/2/tutorial/modules.html

这里还有另一个未提及的区别。这是从http://docs.python.org/2/tutorial/modules.html逐字复制的

Note that when using

注意,当使用

from package import item

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

相反,在使用语法时

import item.subitem.subsubitem

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.

除最后一项外,每一项都必须是一个包裹;最后一项可以是模块或包,但不能是在前一项中定义的类、函数或变量。

#8


4  

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.

再加上人们在x import中说过的内容*:除了让人更难知道名称来自哪里之外,这还会引发像Pylint这样的代码检查。它们将这些名称作为未定义的变量进行报告。

#9


4  

I've just discovered one more subtle difference between these two methods.

我刚刚发现了这两种方法之间更微妙的区别。

If module foo uses a following import:

如果模块foo使用以下导入:

from itertools import count

Then module bar can by mistake use count as though it was defined in foo, not in itertools:

然后模块条可以错误地使用count,就好像它是在foo中定义的,而不是在itertools中:

import foo
foo.count()

If foo uses:

如果foo用途:

import itertools

the mistake is still possible, but less likely to be made. bar needs to:

这个错误仍然是可能的,但不太可能发生。酒吧需要:

import foo
foo.itertools.count()

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.

这给我带来了一些麻烦。我有一个模块,错误地从没有定义它的模块导入了一个异常,只从其他模块导入它(使用模块导入SomeException)。当导入不再需要并删除时,这个问题模块就被破坏了。

#10


3  

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 just import because that means that each module reference is self-documenting. I can see where each symbol comes from without having to hunt around.

我自己的答案主要取决于首先,我将使用多少不同的模块。如果我只使用一到两个,我会经常使用from…因为它在文件的其余部分减少了击键,但是如果我要使用许多不同的模块,我更喜欢导入,因为这意味着每个模块引用都是自文档化的。我可以看到每个符号的来源,而不用四处搜寻。

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.

通常我更喜欢用自己的方式来记录简单的进口,而只是从……当我必须键入模块名的次数在10到20之间时,即使只有一个模块被导入,也需要导入。

#11


2  

import package
import module

With import, the token must be a module (a file containing Python commands) or a package (a folder in the sys.path containing a file __init__.py.)

对于导入,标记必须是模块(包含Python命令的文件)或包(sys中的文件夹)。包含文件__init__.py的路径。

When there are subpackages:

当有子包:

import package1.package2.package
import package1.package2.module

the requirements for folder (package) or file (module) are the same, but the folder or file must be inside package2 which must be inside package1, and both package1 and package2 must contain __init__.py files. https://docs.python.org/2/tutorial/modules.html

文件夹(包)或文件(模块)的要求是相同的,但是文件夹或文件必须在package2中,而package1和package2都必须包含__init__。py文件。https://docs.python.org/2/tutorial/modules.html

With the from style of import:

进口风格:

from package1.package2 import package
from package1.package2 import module

the package or module enters the namespace of the file containing the import statement as module (or package) instead of package1.package2.module. You can always bind to a more convenient name:

包或模块将包含导入语句的文件的名称空间输入为模块(或包),而不是package1.package2.module。你可以用一个更方便的名字:

a = big_package_name.subpackage.even_longer_subpackage_name.function

Only the from style of import permits you to name a particular function or variable:

只有从输入样式允许您命名一个特定的函数或变量:

from package3.module import some_function

is allowed, but

是可以的,但

import package3.module.some_function 

is not allowed.

是不允许的。

#12


0  

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.

模块导入-较少的键入和更多的控制项的模块可以被访问。要使用模块中的新项,必须更新导入语句。

#13


0  

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:

由于我也是一个初学者,我将尝试用简单的方式来解释这一点:在Python中,我们有三种类型的导入语句:

1. Generic imports:

1。一般进口:

import math

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:

这种类型的导入是我个人最喜欢的,这种导入技术唯一的缺点是,如果您需要使用任何模块的函数,您必须使用以下语法:

math.sqrt(4)

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:

使用这个导入语句可以进一步减少输入工作:

import math as m

now, instead of using math.sqrt() you can use m.sqrt().

现在,您可以使用m.s rrt()而不是math.sqrt()。

2. Function imports:

2。功能导入:

from math import sqrt

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.

如果您的代码只需要从模块访问单个或很少的函数,那么这种类型的导入是最合适的,但是对于从模块中使用任何新项,您必须更新import语句。

3. Universal imports:

3所示。普遍的进口:

from math import 

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