Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of R's ls() function in Python to remove all created objects

I am new in Python. There is a function in R called ls(). I can easily remove any created objects using ls() and rm() functions as bellow.

R Code

# 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 

In this post someone suggested an equivalent of ls() in python. So, I have tried to do the same operation in python.

Python Code

# 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

But the problem is when x is recreated and printed it is throwing error:

# Recreate x
x = 1

# Try to print x
x

Traceback (most recent call last):

File "", line 1, in x

File "C:\SomePath\Anaconda\lib\site-packages\IPython\core\displayhook.py", line 258, in call self.update_user_ns(result)

File "C:\SomePath\Anaconda\lib\site-packages\IPython\core\displayhook.py", line 196, in update_user_ns if result is not self.shell.user_ns['_oh']:

KeyError: '_oh'

I have noticed dir() give some extra objects other than my objects. Is there any function which will give the same output like R's ls()?

like image 817
Raja Avatar asked Aug 19 '26 20:08

Raja


2 Answers

There are different questions here.

Is this code correct?

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

No it is not! First dir() returns the keys from the local mapping. At module level, it is the same as globals(), but not inside a function. Next it contains some objects that you do not want to remove like __builtins__...

Is there any function which will give the same output like R's ls()?

Not exactly, but you can try to mimic it with a class:

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]

When you create a cleaner object, it keeps a list (more exactly a set object) of all pre-existing objects. When you call its clean method, it removes from its globals() mapping all objects that were added since its creation (including itself!)

Example (with uncommented tracing):

>>> 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__']
like image 79
Serge Ballesta Avatar answered Aug 22 '26 09:08

Serge Ballesta


Coming from R, the most satisfactory solution I've found is to simply restart the kernel. The downside is that you lose all your imports, but I've learned to live with that.

like image 31
Charles Becker Avatar answered Aug 22 '26 10:08

Charles Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!