2013-06-29 25 views
6

说我有两个Python模块:Python的礼仪:导入模块

module1.py

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

module2.py

def myFunct(): print "called from module2" 
def someFunct(): print "also called from module2" 

如果我输入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到:也

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

,通过导入*,帮助( '模块1')显示所有:

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

现在,在someotherfile.py,我能做到这一点来自module2的功能。

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

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

再次,这是更好的礼仪和实践?要再次输入module2,还是只想参考module1的输入?

回答

2

只是import module2。由于Python在sys.modules中缓存模块对象,重新导入相对来说成本较低。

此外,如module1.module2.myFunct中的链接点违反了Law of Demeter。也许有一天,你会想要替换module1与其他模块module1a哪些不导入module2。通过使用import module2,您将避免必须重写所有出现的module1.module2.myFunct

from module2 import *通常是一种不好的做法,因为它很难追踪变量的来源。混合模块名称空间可能会产生变量名称冲突。例如,from numpy import *是一个确定的否定,因为这样做会覆盖Python的内建sum,min,max,any, all,abs,round

3

引述PEP 8 style guide

当导入从一个包含类模块类,它通常是好拼写这样的:

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

如果拼写引起局部名字冲突,然后拼出它们

import myclass 
import foo.bar.yourclass 

强调我的。

请勿使用module1.module2;您正在依靠module1的内部实现细节,该细节稍后可能会更改它正在使用的导入。您可以直接导入module2,这样做除非模块作者另有说明。

可以使用__all__ convention来限制从与from modulename import *模块进口的; help()命令也会列出该列表。清单名称您明确导出__all__帮助清理help()文本表示:

公共名由模块定义的通过检查模块的名称空间名为__all__变量确定;如果定义了它,它必须是由该模块定义或导入的名称的字符串序列。 __all__中给出的名称都被认为是公开的,并且必须存在。如果未定义__all__,则公用名称集合将包含模块名称空间中的所有名称,该名称不以下划线字符开头('_')。 __all__应该包含整个公共API。它旨在避免意外导出不属于API的项目(例如在模块中导入和使用的库模块)。