Python礼仪:导入模块

2024-09-28 21:50:18 发布

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

假设我有两个Python模块:

module1.py

import module2
def myFunct(): print "called from module1"

module2.py

^{pr2}$

如果我导入module1,那么重新导入module2是更好的礼节呢,还是直接将其称为module1.module2?在

例如(someotherfile.py):

import module1
module1.myFunct() # prints "called from module1"
module1.module2.myFunct() # prints "called from module2"

我也可以这样做:module2 = module1.module2。现在,我可以直接调用module2.myFunct()。在

但是,我可以将module1.py更改为:

from module2 import *
def myFunct(): print "called from module1"

现在,在someotherfile.py中,我可以这样做:

import module1
module1.myFunct() # prints "called from module1"; overrides module2
module1.someFunct() # prints "also called from module2"

另外,通过导入*,help('module1')显示了module2中的所有函数。在

另一方面,(假设module1.py使用import module2),我可以做到: someotherfile.py

 import module1, module2
 module1.myFunct() # prints "called from module1"
 module2.myFunct() # prints "called from module2"

再说一次,哪种礼仪和实践更好?再次导入module2,还是仅仅引用module1的导入?在


Tags: 模块frompyimportdefprintsmodule1print
2条回答

引用PEP 8 style guide

When importing a class from a class-containing module, it's usually okay to spell this:

from myclass import MyClass
from foo.bar.yourclass import YourClass

If this spelling causes local name clashes, then spell them

import myclass
import foo.bar.yourclass

强调我的。在

不要使用module1.module2;您依赖的是module1的内部实现细节,这可能会在以后更改它所使用的导入。您可以直接导入module2,除非模块作者另有说明,否则请这样做。在

您可以使用^{} convention来限制从带有from modulename import *的模块导入的内容;help()命令也遵循该列表。列出您在__all__中显式导出的名称有助于清理help()文本演示:

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

只要import module2。由于Python将模块对象缓存在sys.modules中,因此重新导入相对来说没有成本。在

此外,module1.module2.myFunct中的链式点违反了Law of Demeter。也许有一天你会想用另一个不导入module2的模块来替换{}。通过使用import module2,您将避免重写{}的所有出现。在

from module2 import *通常是一种不好的做法,因为它使跟踪变量的来源变得困难。混合模块名称空间可能会导致变量名冲突。例如,from numpy import *是一个明确的no,因为这样做会覆盖Python的内置代码summinmaxanyallabs和{}。在

相关问题 更多 >