惰性模块变量-可以完成吗? [英] Lazy module variables--can it be done?
问题描述
我正在尝试寻找一种方法来延迟加载模块级变量.
I'm trying to find a way to lazily load a module-level variable.
具体来说,我已经编写了一个微型Python库来与iTunes通讯,并且我想拥有一个DOWNLOAD_FOLDER_PATH
模块变量.不幸的是,iTunes不会告诉您它的下载文件夹在哪里,因此我编写了一个函数,该函数可以捕获一些播客轨道的文件路径,然后向上爬回目录树,直到找到下载"目录.
Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a DOWNLOAD_FOLDER_PATH
module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a few podcast tracks and climbs back up the directory tree until it finds the "Downloads" directory.
这需要一两秒钟,所以我希望对它进行延迟评估,而不是在模块导入时进行评估.
This takes a second or two, so I'd like to have it evaluated lazily, rather than at module import time.
第一次访问模块变量时,是否有任何方法可以懒惰地分配它?还是必须依赖一个函数?
Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?
推荐答案
您无法使用模块来做到这一点,但是您可以伪装一个类,就好像它是一个模块一样,例如在itun.py
中. ..:
You can't do it with modules, but you can disguise a class "as if" it was a module, e.g., in itun.py
, code...:
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()
现在任何人都可以import itun
...,并实际上获得您的itun._Sneaky()
实例. __getattr__
可以让您访问itun.py
中的其他任何内容,这些内容可能比在_Sneaky
内更方便地编码为顶级模块对象!_)
Now anybody can import itun
... and get in fact your itun._Sneaky()
instance. The __getattr__
is there to let you access anything else in itun.py
that may be more convenient for you to code as a top-level module object, than inside _Sneaky
!_)
这篇关于惰性模块变量-可以完成吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!