Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undo "import math" in python?

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?

like image 514
Cindy Avatar asked Jun 06 '18 02:06

Cindy


People also ask

Can you Unimport something in Python?

You can use https://pypi.org/project/unimport/, it can find and remove unused imports for you.

How do you delete an import in Python?

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.

Can you reimport a module Python?

1 Answer. You can re-import a module in python, by using the importlib and its function reload.

How do you de import in Python?

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.


1 Answers

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")
like image 134
aripy887 Avatar answered Oct 24 '22 10:10

aripy887