Python real time class methods
Python is a great programming language with countless merits. However, one short coming (compared with Matlab e.g.) is that one often has to restart the program in order to refresh the modified the code, which is kind of a hassle. Below, I will show what I did to circumvent this problem. Basically, I define the class method in another file, say methods.py, which is different from the file that contains the definition of the class, say myclass.py. Then I found a way to reload (or redefine) all the instance (or class) methods.
class MyClass():
def __init__(self):
import methods as methods;
self.add_extended_methods(methods);
pass;
def add_extended_methods(self, methods):
import inspect;
if not methods.lazy:
reload(methods);
self.methods=methods;
modulefile=inspect.getfile(methods);
modulefile=modulefile.replace('.pyc','.py');
for k in methods.__dict__.keys():
expr="methods."+k;
v=eval(expr);
if inspect.isfunction(v) and inspect.getfile(v)==modulefile:
cmd="def "+k+"(self,*args, **kwargs):return self.methods."+k+"(self,*args, **kwargs);"
exec(cmd);
import new;
cmd="self."+k+"=new.instancemethod("+k+", self, MyClass)";
exec(cmd);
One can also call the "add_extended_methods" anytime when he wants to use updated methods.
This saved me a lot of time from restarting the whole Python/Program
No comments:
Post a Comment