一种选择是创建一个自定义FakeModule
类来处理__getattr__
和分发适当的存根函数/值:
>>> class FakeModule:
... def __getattr__(self, name):
... print name
... return name
...
>>> sys.modules['fakeModule'] = FakeModule()
>>> from fakeModule import something
__path__
something
something
>>> something
'something'
与上面的快速概念证明相比,实际代码需要更多的思考,可能会返回一个 lambda,因此您至少可以执行导入的值。
你可能想做这样的事情:
from functools import wraps
class FakeModule(object):
def __init__(self):
self.module = __import__("module_to_fake")
@staticmethod
def __testWrapper(fn):
@wraps(fn)
def wrapped(*args):
print "%s called with args %s" % (fn.__name__, args)
result = fn(*args)
print " Result was %s" % (result,)
return result
return wrapped
def __getattr__(self, name):
try:
result = getattr(module, name)
except AttributeError:
print "tried to get %s, which does not exist" % name
result = None
if hasattr(result, "__call__"):
result = self.__testWrapper(result)
return result