This is for Python 2.7. I don’t know if it works in other versions.
Sometimes you’re working on a Python module, and you’re testing it from a Python terminal. How do you update the module? If you try to just import again, Python checks and finds it’s already imported, so your new code doesn’t get in. You have to delete the module, then remove it from the Python system, then import it again. Here’s a function that does that.
def r(what): s="import sys\n" s+="import "+what+"\n" s+="del "+what+"\n" s+="sys.modules.pop('"+what+"')\n" s+="import "+what+"\n" return s
So if you put that in r.py and put that in your Python library folder, you’d first do
When you wanted to update, say, your midi library, you’d do
The reason we have to use exec and return Python code in a string is that import wont work unless invoked from the main environment. Calling exec with “import x” imports x into the main environment. Calling a function in module r which imports x does not import x into the main environment.
The reason we import the module to be updated up front is to avoid error messages when you call the function without having previously imported the module you’re calling it on.