Deprecating reload() ???

Skip Montanaro skip at
Fri Mar 12 15:20:14 CET 2004


    >> del sys.modules['modulename']; import modulename


    >> del modulename ; import modulename

Peter sez:

    Peter> Just to clarify, *neither* of the above solutions does anything
    Peter> useful, as far as I know.  Only reload() will really reload a
    Peter> module.  Certainly the del mod/import mod approach is practically
    Peter> a no-op...

Not so.  del sys.modules['mod']/import mod is effectively what reload()
does.  Given with this content:

    a = 1
    print a

here's a session which shows that it is outwardly the same as reload(...).
That is, the module-level code gets reexecuted (precisely because there's
not already a reference in sys.modules).

    >>> import foo
    >>> reload(foo)
    <module 'foo' from 'foo.pyc'>
    >>> import foo
    >>> import sys
    >>> del sys.modules['foo']
    >>> import foo

David MacQuigg's contention that it doesn't work is missing the fact that
when he executed 

    a = testimport.a

he simply created another reference to the original object which was outside
the scope of the names in testimport.  Reloading testimport created a new
object and bound "testimport.a" to it.  That has nothing to do with the
object to which "a" is bound.  This is the problem reload() doesn't solve.

Given Python's current object model it would be an interesting challenge to
write a "super reload" which could identify all the objects created as a
side effect of importing a module and for those with multiple references,
locate those other references by traversing the known object spaces, then
perform the import and finally rebind the references found in the first
step.  I thought I saw something like this posted in a previous thread on
this subject.

In case you're interested in messing around with this, there are three
object spaces to be careful of, builtins (which probably won't hold any
references), all the imported module globals (which you can find in
sys.modules) and all the currently active local Python functions (this is
where it gets interesting ;-).  There's a fourth set of references
- those held by currently active functions which were defined in
extension modules - but I don't think you can get to them from pure Python
code.  Whether or not that's a serious enough problem to derail the quest
for super_reload() function is another matter.  Most of the time it probably
won't matter.  Every once in a great while it will probably bite you in the
ass.  Accordingly, if super_reload() can't track down all the references
which need rebinding it should probably raise a warning/exception or return
a special value to indicate that.


More information about the Python-list mailing list