python re import_Python:“ de-import”,“ re-import”,“ reset import”?

I debug (in PyCharm) a script. I stop at a breakpoint, then I go to the debug console window and from there, I invoke an import line, like this:

import my_util1 from my_utils

Then I call my_util1. So far, everything is OK. Then I change something in "my_util1". Now I would like to call the (updated) my_util1 but I cannot: the system (Python? Pycharm?) "sees" only the previous version of my_util1.

Is there a possibility to "reset" (refresh) what I imported earlier, or to "re-import" it, other than exiting PyCharm and restarting the project?

It is not about dynamically changing the actual code that is being debugged. The task that I am looking for is simpler - it would suffice just to undo an 'import' operation, or to reset/clear/refresh all 'imports' at once. Additionally, the action could be done within the debugger window, not in the code window.

解决方案

sys.modules can be manipulated to change Python's ideas of what's currently imported. To quote the Python docs:

This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail.

Sample usage:

import sys

import my_util1 from my_utils

# Now sys.modules['my_utils'] exists and my_util1 is a local name.

del sys.modules['my_utils']

# my_util1 still exists as a local name, but Python has "forgotten" the import.

import my_util1 from my_utils

# This re-imports my_utils and binds the new my_util1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值