How to reload python module imported using `from module import *`

I agree with the "don't do this generally" consensus, but...

The correct answer is:

import X
reload(X)
from X import Y  # or * for that matter

Never use import *; it destroys readability.

Also, be aware that reloading modules is almost never useful. You can't predict what state your program will end up in after reloading a module, so it's a great way to get incomprehensible, unreproduceable bugs.


A cleaner answer is a mix of Catskul's good answer and Ohad Cohen's use of sys.module and direct redefinition:

import sys
Y = reload(sys.module["X"]).Y  # reload() returns the new module

In fact, doing import X creates a new symbol (X) that might be redefined in the code that follows, which is unnecessary (whereas sys is a common module, so this should not happen).

The interesting point here is that from X import Y does not add X to the namespace, but adds module X to the list of known modules (sys.modules), which allows the module to be reloaded (and its new contents accessed).

More generally, if multiple imported symbols need to be updated, it is then more convenient to import them like this:

import sys
reload(sys.module["X"])  # No X symbol created!
from X import Y, Z, T