How to reload python module imported using `from m

2019-01-10 18:57发布

问题:

I saw in this useful Q&A that one can use reload(whatever_module) or, in Python 3, imp.reload(whatever_module).

My question is, what if I had said from whatever_module import * to import? Then I have no whatever_module to refer to when I use reload(). Are you guys gonna yell at me for throwing a whole module into the global namespace? :)

回答1:

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


回答2:

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.



回答3:

A

from module import *

takes all “exported” objects from module and binds them to module-level (or whatever-your-scope-was-level) names. You can reload the module as:

reload(sys.modules['module'])

but that won't do you any good: the whatever-your-scope-was-level names still point at the old objects.



回答4:

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


回答5:

When importing using from whatever_module import whatever, whatever is counted as part of the importing module, so to reload it - you should reload your module. But just reloading your module you will still get the old whatever - from the already-imported whatever_module, so you need to reload(whatever_module), and than reload your module:

# reload(whatever_module), if you imported it
reload(sys.modules['whatever_module'])
reload(sys.modules[__name__])

if you used from whatever_module import whatever you can also consider

whatever=reload(sys.modules['whatever_module']).whatever

or

whatever=reload(whatever_module).whatever


回答6:

for python 3.7 :

from importlib import reload #import function "reload"
import YourModule #import your any modules
reload(YourModule) #reload your module

Reload function can be called from your own function

def yourFunc():
   reload(YourModule)


回答7:

import re

for mod in sys.modules.values():
    if re.search('name', str(mod)):
        reload(mod)