我目前正在使用jupyter笔记本,我想删除仅在单元格内使用的变量,这样我就不会意外地在其他单元格中滥用这些变量。
例如,我想删除以下代码中的变量myvar和循环变量:i
start = 1
stop = 2
for i in range(start, stop):
pass
myvar = "A"
# other statements
# ...
del i, myvar # Runs ok, and variables i and myvar are deleted and I won't accidentally use i or myvar in another jupyter notebook cell
这工作得很好,但在某些情况下,某些变量实际上没有定义。在下面的示例中,这会引发错误,因为i未定义,因为循环从未运行。定义的变量myvar不会被删除。
start = 1
stop = 1 # Now we have stop equal to 1
for i in range(start, stop):
pass
myvar = "A"
# other statements
# ...
del i, myvar # NameError, since i is not defined, and myvar is not deleted
我已经使用contextlib或try- except语句来避免错误,但仍然myvar没有被删除。
import contextlib
start = 1
stop = 1
for i in range(start, stop):
pass
myvar = "A"
# other statements
# ...
with contextlib.suppress(NameError):
del i, myvar # Error suppressed, but myvar is not deleted
唯一的解决方法是为每个要删除的变量包装 del 语句。
import contextlib
start = 1
stop = 1
for i in range(start, stop):
pass
myvar = "A"
# other statements
# ...
with contextlib.suppress(NameError):
del i
with contextlib.suppress(NameError):
del myvar
# ...
# It works but codes get messy if I need to delete many variables
然而,这会使代码变得混乱,尤其是当您有很多变量需要删除时(如果有 n 个变量则需要删除 n 行)。有没有办法用一两行代码安全地删除所有已定义和未定义的变量,并减少混乱的代码?
慕妹3146593
MMTTMM
斯蒂芬大帝
相关分类