删除匹配指定名称模式的 python 个变量

Delete python variables matching specifing name pattern

有没有办法清除 Python 匹配特定名称字符串模式的变量? 例如,设:

a = 1
b = 2
ab = 3

所以我们可以使用某种 del a* 表达式来删除名称以 a 开头的所有变量(上例中的 aab)。

请不要这样做。但是是的,这是可能的。

通过使用内置函数 vars, it is of course also possible to use globals 作为@Sujal 的回答状态,获取包含范围内变量的字典,然后遍历它们,找到以 a 开头的那些,并将其删除。 然后,当我们这样做时,清理变量 v(因为为什么不这样做)。

a = 2
b = 1
ab = 3

# Copy all vars and delete those that start with a
for v in vars().copy():
    if v.startswith('a'):
        del vars()[v]
    del v

print(b)
print(a)

这会产生

1
Traceback (most recent call last):
  File "[...]/main.py", line 12, in <module>
    print(a)
NameError: name 'a' is not defined

有可能,要不要考虑,但是评论里说这样不好。

有一个内置函数 globals,如文档中所述:

Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.

它基本上是一个包含所有全局变量(和其他对象)的字典,因此如果您从该字典中删除一个项目,那么该变量也将被删除。

利用以上信息,您可以使用以下代码:

matches = [var for var in globals().keys() if var.startswith("a")]
for match in matches:
    del globals()[match]

您可以将 matches 列表更改为您喜欢的任何模式,您可以使用正则表达式进行更复杂的删除。

可以提出以下任何变体:

def mydel(regexp):
    targets = globals().copy()
    for target in targets:
        if re.match(regexp, target):
            globals().pop(target)

这将更新 globals() 字典,该字典跟踪哪些变量是可访问的。

现在,您询问了内存管理,所以问题仍然是从 globals() 字典中删除变量是否真的会触发它被删除。 为此,我们可以检查我们删除的变量指向的对象的生命周期是否真的结束了。这可以通过导入 ctypes 在 cpython 中完成。

import ctypes
h1, h2, h3 = 1, 2, 3
id_check = id(h1)

mydel(r'h.*')

尝试使用任何变量表明它确实如预期的那样不可访问:

h1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/var/folders/81/h94bb5fx2cs6chrwgdsvn4cr0000gp/T/ipykernel_70978/1500632009.py in <module>
----> 1 h3

NameError: name 'h3' is not defined

但是,如果我们使用 ctypes 来查询对象 ID...

ctypes.cast(id_check, ctypes.py_object).value
1

这表明内存还没有被释放。