Alex Rivera | Logout

Reload component Y imported with 'from X import Y'

Asked 2009-11-16T03:41:28.677
145

In Python, once I have imported a module X in an interpreter session using import X, and the module changes on the outside, I can reload the module with reload(X). The changes then become available in my interpreter session.

I am wondering if this also possible when I import a component Y from module X using from X import Y.

The statement reload Y does not work, since Y is not a module itself, but only a component (in this case a class) inside of a module.

Is it possible at all to reload individual components of a module without leaving the interpreter session (or importing the entire module)?

For clarification, the question is about importing a class or function Y from a module X and reloading on a change, not a module Y from a package X.

Edit
Report

2 Answers

57

If Y is a module (and X a package) reload(Y) will be fine -- otherwise, you'll see why good Python style guides (such as my employer's) say to never import anything except a module (this is one out of many great reasons -- yet people still keep importing functions and classes directly, no matter how much I explain that it's not a good idea;-).

answered 2009-11-16T03:44:48.037
6

First off, you shouldn't be using reload at all, if you can avoid it. But let's assume you have your reasons (i.e. debugging inside IDLE).

Reloading the library won't get the names back into the module's namespace. To do this, just reassign the variables:

f = open('zoo.py', 'w')
f.write("snakes = ['viper','anaconda']\n")
f.close()

from zoo import snakes
print snakes

f = open('zoo.py', 'w')
f.write("snakes = ['black-adder','boa constrictor']\n")
f.close()

import zoo
reload(zoo)
snakes = zoo.snakes # the variable 'snakes' is now reloaded

print snakes

You could do this a few other ways. You could automate the process by searching through the local namespace, and reassigning anything that was from the module in question, but I think we are being evil enough.

answered 2009-11-16T06:21:51.513

Your Answer