Autoreloader for python
I was discussing ways to get python to automatically reload modules (useful when using matplotlib to try out algorithms and stuff) and came up with the following:
class Autoreloader:
def __init__(self,moduleName,path = None):
self._moduleName = moduleName
self._path = path
def __getattr__(self,attr):
import inspect
import imp
import sys
sys.path.append(self._path)
_module = imp.load_module(self._moduleName,*imp.find_module(self._moduleName))
sys.path.remove(self._path)
if attr == "__members__":
return [a[0] for a in inspect.getmembers(_module,inspect.isfunction)]
else:
return _module.__dict__[attr]
Then instead of doing
import my_module
you do
my_module = Autoreloader("my_module")
After that you can add a function to my_module.py, go back to ipython, and type my_module.<TAB> and your function will magically appear! To change the function just hit ctrl-S in your text editor and the next time you run the function it will pick up the changes.
This does incur a performance hit and this is version 0.1 I'm sure it can be improved...
Posted on Thursday, May 22, 2008 at 3:42 PM
Post a Comment