Programming Tutorials

How to force rereading of a changed module in python

By: Python Team in Python Tutorials on 2012-04-07  

For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn"t, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force rereading of a changed module, do this:

import imp
import modname
imp.reload(modname)
Warning: this technique is not 100% fool-proof. In particular, modules containing statements like
from modname import some_objects

will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will not be updated to use the new class definition. This can result in the following paradoxical behaviour:

>>> import imp
>>> import cls
>>> c = cls.C() # Create an instance of C
>>> imp.reload(cls)
<module 'cls' from 'cls.py'>
>>> isinstance(c, cls.C) # isinstance is false?!?
False

The nature of the problem is made clear if you print out the "identity" of the class objects:

>>> hex(id(c.__class__))
'0x7352a0'
>>> hex(id(cls.C))
'0x4198d0'





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)