我想编写一个python包,它会在您尝试导入时动态创建可导入的对象。
IE,如果你写
from importTest import importable
当您输入时,它会定义importable
。
我想也许我可以通过覆盖模块上的__getattribute__
来做到这一点,如下所示,但这不起作用:
import sys
def getService(self, name):
# Ultimately, I want this to query a web service and create objects
# as you attempt to import them. Defining them all in advance
# would make for far too heavy a download, as there are hundreds of
# thousands defined, and users typically use 2-3.
# For now, just to test if this dynamic import idea works,
# just return the string with the name.
return name + '!'
sys.modules[__name__].__getattribute__ = getService
在你嗤之以鼻并想知道为什么我认为这可能有效之前,这确实有效,只是,它不够动态......我需要它来定义属性,直到它真正知道用户正在尝试的名称进口。
import sys
sys.modules[__name__].importable = 'importable!'