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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With