A cleaner answer is a mix of Catskul's good answer and Ohad Cohen's use of sys.modules
and direct redefinition:
import sys
Y = reload(sys.modules["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.modules["X"]) # No X symbol created!
from X import Y, Z, T