Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python reload module for beginner. importlib.reload doesn't seem to work

I have a file called skdb and class called skmysqldb. I am trying to force reload.

I tried reloading "skdb", "skdb.skmysqldb" "skmysqldb" and none of them seem to work.

>>> from skdb import skmysqldb

>>> importlib.reload(skdb.skmysqldb)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'skdb' is not defined

>>> importlib.reload(skmysqldb)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 139, in reload
    raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module

>>> importlib.reload(skdb)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'skdb' is not defined
like image 431
Nite Avatar asked Sep 09 '26 05:09

Nite


2 Answers

When you import some object using the from <module> import <obj> syntax as in

from skdb import skmysqldb

the module itself is not added to the current namespace, hence why you get a NameError when you try to do reload(skdb).

Instead try:

import skdb
importlib.reload(skdb)

Be cautious when using reload. If the module your reload imports other modules, those modules are not reloaded recursively, so depending on the exact code you can wind up in a rather broken state where it's better to just restart the whole interpreter.

like image 192
Iguananaut Avatar answered Sep 10 '26 17:09

Iguananaut


I don't think this is supported, but try doing del sys.modules['mymodule'] for everything that vaguely matches. To find relevant ones, try something like [x for x in sys.modules if 'mymodule' in x].

like image 22
Anon Avatar answered Sep 10 '26 17:09

Anon