如何在Python中取消导入"math"模块?

7

在Python中导入一个模块后,如何在同一工作空间中撤销其影响?

例如,在Python IDLE中输入“import random”后,我想在同一工作空间中删除模块“random”中导入的所有函数,我该怎么做?


3
可能是 如何取消导入已经导入的 Python 模块? 的重复问题。 - user3483203
很遗憾,没有真正的“取消导入”的方法,您只能删除对它的引用。 - user3483203
2
你为什么想要这样做? - Maarten Fabré
1个回答

3
您可以尝试将导入和使用该导入的代码包装在特定作用域中。这样一来,一旦作用域退出,导入的库就不再可用。
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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接