Вот моя попытка. Я думаю, что с метаклассами можно сделать более хороший подход ...
to_import_from.py:
def external_method(self, arg1, arg2):
if self.flag:
print "flag is set"
else :
print "flag is not set"
instrument.py:
import imp
import os
import inspect
import new
import pdb
class MethodImporter(object) :
def __init__(self, path_to_module) :
self.load_module(path_to_module)
def load_module(self, path_to_module) :
name = os.path.basename(path_to_module)
module_file = file(path_to_module,"r")
self.module = imp.load_module(name, module_file , path_to_module, ('','r',imp.PY_SOURCE))
print "Module %s imported" % self.module
for method_name, method_object in inspect.getmembers(self.module, inspect.isfunction) :
print "adding method %s to %s" % (method_name, self)
setattr(self, method_name, new.instancemethod(method_object, self, self.__class__))
class Instrument(MethodImporter):
def __init__(self):
super(Instrument,self).__init__("./to_import_from.py")
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
при запуске этого кода
arg1, arg2 = 1, 2
instr = Instrument()
instr.direct_method(arg1)
instr.external_method(arg1, arg2)
вот вывод:
Module <module 'to_import_from.py' from './to_import_from.pyc'> imported
adding method external_method to <__main__.Instrument object at 0x2ddeb0>
flag is set
flag is set