0
$\begingroup$

If I import a module using from . import *module* – this module could be reloaded via importlib.reload(*module*)

BUT if the same module was imported using importlib.import_module(*module_name*) – then importlib.reload() has no effect.

I both cases I was using the following code for reloading modules:

for module in list(sys.modules):
   if module.startswith(__package__ + '.'):
      importlib.reload(sys.modules[module])

The question: how can I reload a module which was imported using importlib.import_module ?



UPD:

Finally I've figured what caused the problem:

in sys.modules after the direct import modules look like: package.module_name

but when import is via importlib they look like:

module_name

*so no package name mentioned.

Therefore they just could not be located with if module.startswith(__package__ + '.')

Because there are neither package name nor the . symbol.

To me it seems quite odd, what importlib omits the package name...

But it is how it is.

$\endgroup$
3
  • $\begingroup$ Should work. importlib.import_module(__package__ + '.test_msg') would work for your previous question setup. Make sure those are the same modules you importing and reloading. Share your code. $\endgroup$
    – unwave
    Apr 7 at 4:45
  • 1
    $\begingroup$ The thing is: it should not omit the packaged name. If it is then you are not importing it as a part of a package. importlib.import_module(__package__ + '.test_msg').__name__ == 'TEST_MSG.test_msg' which is equivalent to from . import test_msg $\endgroup$
    – unwave
    Apr 8 at 0:38
  • $\begingroup$ @unwave — Omg, I was doing importing wrong the whole way. Huge thanks for info. Post your comment as an answer — I will grant you a bounty. You totally deserve it. $\endgroup$
    – Yaroslav
    Apr 8 at 13:33

1 Answer 1

1
+50
$\begingroup$

from . import test_msg

is equivalent to

test_msg = importlib.import_module('.test_msg', __package__)

or

test_msg = importlib.import_module(__package__ + '.test_msg')

Name in sys.modules is TEST_MSG.test_msg: test_msg.__name__ == 'TEST_MSG.test_msg' It is a part of the package: test_msg.__package__ == 'TEST_MSG'

import test_msg

is equivalent to

test_msg = importlib.import_module('test_msg')

Name in sys.modules is test_msg: test_msg.__name__ == 'test_msg' It is not a part of a package test_msg.__package__ == '' or it might be another package on its own such as test_msg.__package__ == test_msg.__name__ == 'test_msg'.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .