0

I need to COMPLETELY reload a module in python. What I mean by 'completely" is that I don't want the following feature (from the python 2.6 docs for the builtin reload function):

"...If the new version of a module does not define a name that was defined by the old version, the old definition remains...".

I.e. I don't want old names that have vanished in the new module version to be retained.

What is the best practice of achieving this?

Thanks!

frank
  • 481
  • 8
  • 16
  • Why don't you just restart your Python Shell with Ctrl+F? You can still re-call previous commands with ALT+P. – LarsVegas Oct 01 '12 at 08:18
  • @larsvegas: I am not in a python shell, I am dynamically loading code from my program. – frank Oct 01 '12 at 09:09
  • I guess you should look into the [`gc`](http://docs.python.org/library/gc.html#module-gc) module then. – LarsVegas Oct 01 '12 at 09:16

1 Answers1

3

Deleting the module from sys.modules and re-importing could be a start, although I haven't tested it beyond the below:

import itertools

itertools.TEST = 7
reload(itertools)
print itertools.TEST
# 7

import sys
del sys.modules['itertools']
import itertools
print itertools.TEST

#Traceback (most recent call last):
#  File "/home/jon/stackoverflow/12669546-reload-with-reset.py", line 10, in <module>
#    print itertools.TEST
# AttributeError: 'module' object has no attribute 'TEST'

Test with 3rd party module

>>> import pandas
>>> import sys
>>> del sys.modules['pandas']
>>> import pandas
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    import pandas
  File "/usr/local/lib/python2.7/dist-packages/pandas-0.7.3-py2.7-linux-x86_64.egg/pandas/__init__.py", line 10, in <module>
    import pandas._tseries as lib
AttributeError: 'module' object has no attribute '_tseries'
>>> to_del = [m for m in sys.modules if m.startswith('pandas.')]
>>> for td in to_del:
    del sys.modules[td]

>>> import pandas
>>> # now it works
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • Looks good, but is this the recommended way to do it? Are there any gotchas? – frank Oct 01 '12 at 12:30
  • @frank I've got a feeling that if the module itself does some other importing - it may not be particularly robust - I've done another test on a 3rd party module, and it seems to not work if you don't delete any other modules under it (but ummm...) – Jon Clements Oct 01 '12 at 12:36