Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 242
Heath Raftery Avatar asked Nov 14 '25 09:11

Heath Raftery


1 Answers

I found an easy solution:

  1. Import from the module and the module itself.
  2. Then use reload() as usual, but also redo the import from.
>>> 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!
like image 146
Heath Raftery Avatar answered Nov 16 '25 22:11

Heath Raftery