English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

python dynamic loading implementation method

Scripting languages all have an advantage, that is, dynamic loading. Lua language has this advantage, Python also has this feature. To put it simply, if a developer finds that their code has a bug, they can dynamically replace modules without closing the original code. The method of replacement is usually completed by reload.

1Basic principle of reload

reload mainly does two actions, delete the original module, and add a new module

2Equivalent code of reload

del sys.modules[module_name]
__import__(module_name)

3What to pay attention to when using reload

3.1 The entry parameter of reload is module, not a string, that is

import sys
module = sys.modules[module_name]

3.2 The reloaded file is only the __init__.py file of the corresponding module, if it is another file, it will not take effect

3.3 If it is another file in the directory, it needs to be reloaded separately, for example

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

Or

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

Summary

The above-mentioned is the implementation method of dynamic loading of Python introduced by the editor to everyone, hoping it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. Here, I also want to express my heartfelt thanks to everyone for supporting the Yelling Tutorial!

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like