在删除一个变量然后重新加载模块之后,如何使名称空间不保留这个变量?

2024-06-12 02:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

“reload”函数不能删除已加载到内存中的变量,如果您在重新加载之前在模块中删除它。换句话说,即使在重新加载之前删除变量,它仍然存在。你知道吗

根据(DOCS):

When a module is reloaded, its dictionary (containing the module’s global variables) is retained.

下面是一个简单的例子:

import importlib
import time
def main():
    import ex1
    i = 0
    while True:
        importlib.reload(ex1)
        ex1.x = ex1.x + 1
        i = i + 1
        print("loop:%d" %i)
        print("x:%d" %ex1.x)
        print(dir(ex1))
        time.sleep(5)

重新加载前ex1模块的内容:

x = 1
y = 1

然后删除x并重新加载ex1,我们会发现x仍然在dir(ex1)

所以,我的问题是如何得到一个dict,其中x在delete和reload之后不在dir中?你知道吗


Tags: 模块函数内存importdocstimeisdir
1条回答
网友
1楼 · 发布于 2024-06-12 02:28:17

你读得不够多,在你引用的那句话之后:

Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains.

因此,您引用的句子只适用于在旧版本的模块中定义的变量,而不是在新版本的模块中定义的变量。你知道吗

所以对于你的问题:

So, my question is how can I get a dict in which x is not in the dir after delete and reload?

答案是你不能。但是你可以:

del ex1.x

重新加载后。你知道吗

相关问题 更多 >