Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6881

Reloading module in Python: changing value vs removing value inconsistency

While debugging some code using reload built-in, I found some inconsistency of behaviour.

Consider the following interactive session:

Python 2.7.4 (default, Sep 26 2013, 03:20:26) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> foo.BAR
'bar'
>>> # here I edit foo.py, changing BAR to 'foobar'
... 
>>> foo.BAR
'bar'
>>> # as expected
... 
>>> reload(foo)
<module 'foo' from 'foo.py'>
>>> foo.BAR
'foobar'
>>> # as expected
... 
>>> 

all works as expected. But if I remove the value instead of changing it, it doesn't work as expected

Python 2.7.4 (default, Sep 26 2013, 03:20:26) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> foo.BAR
'bar'
>>> # here I edit foo.py, removing BAR from it
... 
>>> foo.BAR
'bar'
>>> # as expected
... 
>>> reload(foo)
<module 'foo' from 'foo.py'>
>>> foo.BAR
'bar'
>>> # ???
... 
>>> 

Why does that happen? Is there a way to reload a module and avoid that issue?

Upvotes: 2

Views: 65

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

Taken from the docs:

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains

Upvotes: 1

otus
otus

Reputation: 5732

I'm not sure why it happens, but you can reload the module fully by first deleting it from module cache:

import sys
del sys.modules['foo']

then reimporting:

import foo

Upvotes: 0

Related Questions