'How do I reload a module if I imported (possibly all) objects from the module rather than the module itself?
If I'm working on a module, say mymod, it's convenient to start an interpreter by importing __all__ from the module, like so:
>>> from mymod import *
Since I'm making changes to mymod, using importlib.reload() is handy. Alas, because I didn't explicitly import the module itself, it doesn't work:
>>> from importlib import reload
>>> reload(mymod)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mymod' is not defined
so I need to restart my Python interpreter session and issue the from mymod import * again to pick up the changes.
Is there a way to reload mymod, even though I'm actually importing from it, not the module itself?
Solution 1:[1]
I found an easy solution:
- Import
fromthe module and the module itself. - Then use
reload()as usual, but also redo the importfrom.
>>> from importlib import reload
>>> from mymod import *
>>> import mymod # <--- Step 1. Only so we can "reload()" it.
>>> # call a function imported from mymod
>>> mymodfunc()
>>> # now edit the source code of mymodfunc()
>>> reload(mymod)
<module 'mymod' from '/path/to/mymod.py'>
>>> from mymod import * # <--- Step 2. Has to be done in this order.
>>> mymodfunc() # runs the modified version!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Heath Raftery |
