Each module is loaded into memory only once during an interpreter session or during a program run, regardless of the number of times it is imported into a program. If multiple imports occur, the module’s code will not be executed again and again.
Suppose during an interactive session, you have imported a module, and the code of the module is changed while you are using these modules. You might want to use the updated module code by importing it again, but this is not possible since any imports that are done after the first import just use the already loaded module object, the module is not reloaded and its code is not executed again. You have to restart the interpreter session or execute the program again to reload the module. However, you can force a reload by using the reload function from the importlib module. This way we can get the updated version of the already loaded module without exiting the interpreter session.
>>> import module1
>>> from importlib import reload
>>> reload(module1)
zzh@ZZHPC:/zdata/Github/python$ python Python 3.12.3 (main, May 16 2024, 09:18:37) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import aaa >>> f = aaa.Fraction(2, 3) >>> print(f) 2/3 >>> str(f) '2/3' >>> f <aaa.Fraction object at 0x76587b535b50> >>> from importlib import reload Added __repr__ for class Fraction. >>> reload(aaa) <module 'aaa' from '/zdata/Github/python/aaa.py'> >>> f <aaa.Fraction object at 0x76587b535b50> >>> f = aaa.Fraction(2, 3) >>> f Fraction(2,3)
reload的更新对已经存在的变量不起作用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-07-30 Python - Modifying Lists/Dictionaries
2023-07-30 Python - Exception Shadowing
2023-07-30 Python - sorted() a tuple
2023-07-30 Python - Conditional Unpacking
2023-07-30 Python - List Anarchy