Python导入的经验法则是什么?

2024-04-27 05:17:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对用Python导入模块的多种方法有些困惑。

import X
import X as Y
from A import B

我一直在阅读有关作用域和名称空间的文章,但我想就什么是最好的策略、在什么情况下以及为什么这样做提出一些切实可行的建议。导入应该在模块级还是方法/功能级进行?在__init__.py中还是在模块代码本身中?

我的问题并没有真正用“Python packages - import by class, not file”来回答,尽管它显然是相关的。


Tags: 模块方法frompyimport功能名称init
3条回答

让我把对话的一部分粘贴到由Guido van Rossum开始的django dev邮件列表上:

[...] For example, it's part of the Google Python style guides[1] that all imports must import a module, not a class or function from that module. There are way more classes and functions than there are modules, so recalling where a particular thing comes from is much easier if it is prefixed with a module name. Often multiple modules happen to define things with the same name -- so a reader of the code doesn't have to go back to the top of the file to see from which module a given name is imported.

来源:http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a

1:http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports

在我们公司的生产代码中,我们试图遵循以下规则。

我们将导入放在文件的开头,紧跟在主文件的docstring之后,例如:

"""
Registry related functionality.
"""
import wx
# ...

现在,如果导入的类是导入模块中为数不多的类之一,则直接导入名称,这样在代码中只需使用最后一部分,例如:

from RegistryController import RegistryController
from ui.windows.lists import ListCtrl, DynamicListCtrl

但是,有些模块包含几十个类,例如所有可能的异常列表。然后我们导入模块本身并在代码中引用它:

from main.core import Exceptions
# ...
raise Exceptions.FileNotFound()

我们尽可能少地使用import X as Y,因为它使搜索特定模块或类的用法变得困难。但是,有时如果希望导入两个同名但存在于不同模块中的类,则必须使用它,例如:

from Queue import Queue
from main.core.MessageQueue import Queue as MessageQueue

一般来说,我们不在方法内部进行导入——它们只是让代码变得更慢,可读性更低。有些人可能会发现这是一个很好的方法来轻松解决循环导入问题,但更好的解决方案是代码重组。

我通常在模块级使用import X。如果只需要模块中的单个对象,请使用from X import Y

只有在遇到名称冲突时才使用import X as Y

当模块用作主模块时,我只使用函数级的导入来导入所需的内容,例如:

def main():
  import sys
  if len(sys.argv) > 1:
     pass

高温高压

相关问题 更多 >