我在 Python 3.3 上使用了 Alex 的实现,但这很糟糕:
代码
def __getattr__(self, name):
return globals()[name]
不正确,因为应该引发 AttributeError,而不是 KeyError。
这在 Python 3.3 下立即崩溃,因为做了很多自省
在导入期间,寻找__path__、__loader__ 等属性。
这是我们现在在项目中使用的允许延迟导入的版本
在一个模块中。模块的__init__ 延迟到第一个属性访问
没有特殊名称的:
""" 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 :-)
Lazy module variables--can it be done?
class _Sneaky(object):
def __init__(self, name):
self.module = sys.modules[name]
sys.modules[name] = self
self.initializing = True
def __getattr__(self, name):
# call module.__init__ after import introspection is done
if self.initializing and not name[:2] == '__' == name[-2:]:
self.initializing = False
__init__(self.module)
return getattr(self.module, name)
_Sneaky(__name__)
模块现在需要定义一个 init 函数。可以使用这个功能
导入可能导入我们自己的模块:
def __init__(module):
...
# do something that imports config.py again
...
代码可以放到另一个模块中,可以用属性扩展
和上面的例子一样。
也许这对某人有用。