Project organization and import
Michele Simionato
michele.simionato at gmail.com
Wed Mar 7 02:18:20 EST 2007
On Mar 5, 1:21 am, "Martin Unsal" <martinun... at gmail.com> wrote:
> 2) Importing and reloading. I want to be able to reload changes
> without exiting the interpreter.
What about this?
$ cat reload_obj.py
"""
Reload a function or a class from the filesystem.
For instance, suppose you have a module
$ cat mymodule.py
def f():
print 'version 1 of function f'
Suppose you are testing the function from the interactive interpreter:
>>> from mymodule import f
>>> f()
version 1 of function f
Then suppose you edit mymodule.py:
$ cat mymodule.py
def f():
print 'version 2 of function f'
You can see the changes in the interactive interpreter simply by doing
>>> f = reload_obj(f)
>>> f()
version 2 of function f
"""
import inspect
def reload_obj(obj):
assert inspect.isfunction(obj) or inspect.isclass(obj)
mod = __import__(obj.__module__)
reload(mod)
return getattr(mod, obj.__name__)
Pretty simple, isn't it?
The issue is that if you have other objects dependending on the
previous version
of the function/class, they will keep depending on the previous
version, not on
the reloaded version, but you cannot pretende miracles from reload! ;)
You can also look at Michael Hudson's recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164
for a clever approach to automatic reloading.
Michele Simionato
More information about the Python-list
mailing list