After I import a module in python, how could I undo the effect in the same python work space?
For example, after I typed "import random" in a python IDLE, I want to remove all the imported functions in the module "random" in the same workspace, how could I do it?
You can use https://pypi.org/project/unimport/, it can find and remove unused imports for you.
To remove an imported module in Python: Use the del statement to delete the sys reference to the module. Use the del statement to remove the direct reference to the module.
1 Answer. You can re-import a module in python, by using the importlib and its function reload.
There is no clean way to deimport modules. Everything you're going to do is through hacks. Get metadata by parsing the code using the ast module instead of importing them, as tools like Epydoc, PyDoctor, and Sphinx do.
You could try to wrap the import and the code using that import in a specific scope. That way once the scope exits, the imported library won't be in reach.
def do_something_with_random():
import random
print("do something interesting with random", random.choice([0, 1]))
print("perform task that don't need random")
do_something_with_random()
print("function call uses random, but doesn't add it to your globals")
print("continue performing tasks that don't need random")
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