""" config.py """
# lazy initialization of this module to avoid circular import.
# the trick is to replace this module by an instance!
# modelled after a post from Alex Martelli :-)
import sys
class _Sneaky(object):
def __init__(self):
self.download = None
@property
def DOWNLOAD_PATH(self):
if not self.download:
self.download = heavyComputations()
return self.download
def __getattr__(self, name):
return globals()[name]
# other parts of itun that you WANT to code in
# module-ish ways
sys.modules[__name__] = _Sneaky()
我在Python3.3上使用了Alex的实现,但这崩溃得很惨: 守则
不正确,因为应该引发
AttributeError
,而不是KeyError
。 这在Python 3.3下立即崩溃,因为已经做了很多内省工作 在导入过程中,查找诸如__path__
、__loader__
等属性下面是我们现在在项目中使用的允许惰性导入的版本 在一个模块中。模块的
__init__
被延迟到第一个属性访问 没有特别的名字:Lazy module variables--can it be done?
模块现在需要定义一个init函数。此功能可以使用 要导入可能自行导入的模块,请执行以下操作:
代码可以放在另一个模块中,并且可以用属性进行扩展 就像上面的例子一样。
也许这对某人有用。
事实证明,从Python 3.7开始,可以通过在模块级定义一个
__getattr__()
来实现这一点,如PEP 562中所指定的。你不能用模块来做,但是你可以把类伪装成一个模块,例如在
itun.py
,代码…:现在任何人都可以
import itun
。。。并获得您的itun._Sneaky()
实例。这里的__getattr__
允许您访问itun.py
中的任何其他内容,这可能比在_Sneaky
中编写顶级模块对象更方便!_)相关问题 更多 >
编程相关推荐