首页 > 解决方案 > 等效于 Python 中 R 的 ls() 函数,用于删除所有创建的对象

问题描述

我是 Python 新手。R 中有一个函数叫做ls(). 我可以使用下面的函数ls()轻松删除任何创建的对象。rm()

代码

# Create x and y
x = 1
y = "a"

# remove all created objects
ls()
# [1] "x" "y"
rm(list = ls())

# Try to print x
x
# Error: object 'x' not found 

这篇文章中,有人提出了ls()在 python 中的等价物。所以,我尝试在 python 中做同样的操作。

Python代码

# Create x and y
x = 1
y = "a"

# remove all created objects
for v in dir(): del globals()[v]

# Try to print x
x
# NameError: name 'x' is not defined

但问题是x重新创建和打印时会抛出错误:

# Recreate x
x = 1

# Try to print x
x

回溯(最近一次通话最后):

文件“”,第 1 行,在 x

文件“C:\SomePath\Anaconda\lib\site-packages\IPython\core\displayhook.py”,第 258 行,调用 self.update_user_ns(result)

如果结果不是 self.shell.user_ns['_oh'],则在 update_user_ns 中的文件“C:\SomePath\Anaconda\lib\site-packages\IPython\core\displayhook.py”,第 196 行:

键错误:'_oh'

我注意到dir()除了我的对象之外,还提供了一些额外的对象。是否有任何函数可以提供与 R 相同的输出ls()

标签: pythonpython-3.x

解决方案


这里有不同的问题。

这段代码正确吗?

# remove all created objects
for v in dir(): del globals()[v]

不它不是!首先dir()从本地映射返回键。在模块级别,它与 相同globals(),但不在函数内部。接下来它包含一些您不想删除的对象,例如__builtins__...

是否有任何函数可以提供与 R 的 ls() 相同的输出?

不完全是,但你可以尝试用一个类来模仿它:

class Cleaner:
    def __init__(self):
        self.reset()
    def reset(self):
        self.keep = set(globals());
    def clean(self):
        g = list(globals())
        for __i in g:
            if __i not in self.keep:
                # print("Removing", __i)      # uncomment for tracing what happens
                del globals()[__i]

当您创建一个更干净的对象时,它会保留set所有预先存在的对象的列表(更准确地说是一个对象)。当你调用它的clean方法时,它会从它的映射中删除globals()自它创建以来添加的所有对象(包括它自己!)

示例(带有未注释的跟踪):

>>> class Cleaner:
    def __init__(self):
        self.reset()
    def reset(self):
        self.keep = set(globals());
    def clean(self):
        g = list(globals())
        for __i in g:
            if __i not in self.keep:
                print("Removing", __i)      # uncomment for tracing what happens
                del globals()[__i]


>>> dir()
['Cleaner', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> c = Cleaner()
>>> i = 1 + 2
>>> import sys
>>> dir()
['Cleaner', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'c', 'i', 'sys']
>>> c.clean()
Removing c
Removing i
Removing sys
>>> dir()
['Cleaner', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

推荐阅读