Python 导入有哪些好的经验法则? [英] What are good rules of thumb for Python imports?

查看:65
本文介绍了Python 导入有哪些好的经验法则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在 Python 中导入模块的多种方式感到有些困惑.

I am a little confused by the multitude of ways in which you can import modules in Python.

import X
import X as Y
from A import B

我一直在阅读有关作用域和命名空间的内容,但我想就什么是最佳策略、在何种情况下以及为什么这样做提供一些实用的建议.导入应该发生在模块级别还是方法/函数级别?在 __init__.py 中还是在模块代码中?

I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the __init__.py or in the module code itself?

Python 包 - 按类导入,并没有真正回答我的问题,不是文件",尽管它显然是相关的.

My question is not really answered by "Python packages - import by class, not file" although it is obviously related.

推荐答案

在我们公司的生产代码中,我们尽量遵循以下规则.

In production code in our company, we try to follow the following rules.

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

We place imports at the beginning of the file, right after the main file's docstring, e.g.:

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

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

Now, if we import a class that is one of few in the imported module, we import the name directly, so that in the code we only have to use the last part, e.g.:

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

然而,有些模块包含数十个类,例如所有可能的例外的列表.然后我们导入模块本身并在代码中引用它:

There are modules, however, that contain dozens of classes, e.g. list of all possible exceptions. Then we import the module itself and reference to it in the code:

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

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

We use the import X as Y as rarely as possible, because it makes searching for usage of a particular module or class difficult. Sometimes, however, you have to use it if you wish to import two classes that have the same name, but exist in different modules, e.g.:

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

作为一般规则,我们不在方法内部进行导入——它们只会使代码变慢和可读性降低.有些人可能会发现这是一种轻松解决循环导入问题的好方法,但更好的解决方案是代码重组.

As a general rule, we don't do imports inside methods -- they simply make code slower and less readable. Some may find this a good way to easily resolve cyclic imports problem, but a better solution is code reorganization.

这篇关于Python 导入有哪些好的经验法则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆