reload from ( was Python FAQ ... )

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Wed, 17 Nov 1993 13:27:37 -0500

On Nov 17, 11:05, tnb2d@henson.cs.virginia.edu wrote:
>
> If I want to get at changes I make to a module I've *import*ed
> without having to quit the interpreter I can use the reload(module)
> call, correct? But if I've *import*ed functions and data *from* the
> module, and not actually *import*ed the module itself this reloading
> doesn't work. I can't re-*import* parts of a module. Why not? I
> understand the desire for caching modules and appreciate it MOST of
> the time, but sometimes I don't want the cached values! There is a
> way provided to defeat that cache (reload) for *import*ed modules when
> I want/need to. How hard would it be to provide a 'from module
> re-import *' call that would defeat the cache and go back to disk for
> these items as well?

There is a non-obvious, kludgey sort of way to do this. Try:

>>>import sys,posix
>>>from xxx import *
>>>posix.system( 'jove xxx.py' )

[ edit xxx.py ... ]

>>>reload( sys.modules['xxx'] )

sys.modules is a dictionary object that contains all of the
imported and cached modules. [ See my previous post on
how to import /usr/local/lib/python/ftplib.py from within
$PWD/ftplib.py ]

I suppose the elegant way would be to make 'reload' a
keyword like 'import', rather than a function. It doesn't
need a from ( demonstrated by the fact that the reload(sys.
modules[]) above DOESN'T put xxx into the namespace. Try
dir() after the reload. ) The problem is that since "xxx"
isn't in the namespace, the expression reload(xxx) doesn't
have "xxx" defined. import/def/class are statements that
create new names in the current namespace.

[ But since I suspect that most uses of reload are with
interactive use and editing, I don't think there is
a real need to add another keyword. ]

Here is an initial stab at a edit+reload command.
I've used something like this before on both dos and
unix, but it previously had just the problem you pointed
out with 'import from'. ( I don't know if the current
0.9.8 dos version has __name__, so I don't know if this
will still work there. )

# editpy( module )
# where type(module) in ( <type 'module'>, < type 'string' > )

import sys,os
_string_type = type('')
_module_type = type(sys)
_default_editor = 'jove'
if os.environ.has_key('VISUAL'):
_editor = os.environ['VISUAL']
elif os.environ.has_key('EDITOR'):
_editor = os.environ['EDITOR']
else: _editor = _default_editor

def editpy( module ):
if type(module) == _string_type:
modname = module
module = sys.modules[modname]
elif type(module) == _module_type:
modname = module.__name__
else: raise TypeError, ' arg must be module or module-name '
os.system( _editor + ' ' + modname + '.py' )
reload( module )

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics