python dynamic loading method

  • 2020-06-19 10:52:12
  • OfStack

Scripting languages have one advantage: dynamic loading. The lua language has this advantage, and so does python. To put it simply, if a developer finds that his code has bug, he can dynamically replace the module without closing the original code. Substitution 1 is usually done with reload.

1. Basic principles of reload

reload does two main actions, removing the original module and adding a new one

2. Equivalent code of reload


del sys.modules[module_name]
__import__(module_name)

3. What should be paid attention to when using reload

3.1 The entry parameter of reload is module, not a string, i.e


import sys
module = sys.modules[module_name]

3.2 The overloaded file is simply the file with the corresponding module es25EN__.py. If it is anything else, it will not take effect

3.3 If it is other files in the directory, they need to be reloaded separately, such as


import sys
del sys.modules['module_name:sub_file']
__import__('module_name:sub_file')

Or is it


reload(sys.modules['module_name:sub_file'])

conclusion


Related articles: