Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to delete variable from self if it exists in a list

I have a list of strings ['foo1', 'foo2', ...] that represent variables that I want to delete from self if they are part of self. What is a Pythonic and compact way to do this?

My first attempt is

if hasattr(self, 'foo1'):
    del self.foo1
if hasattr(self, 'foo2'):
    del self.foo2
...

but this obviously isn't scalable for a large list.

Can anyone help?

like image 511
RoachLord Avatar asked Nov 27 '22 16:11

RoachLord


2 Answers

You can use a for loop and at the same time boost performance by using pop on the __dict__ of the object:

for attr in ('foo1','foo2'):
    self.__dict__.pop(attr,None)

pop basically does a check whether the element is in the dictionary and removes it if that is the case (it also returns the corresponding value, but that is not relevant here). We also use None here as a "default" return value such that if the key does not exists, pop will not error.

like image 87
Willem Van Onsem Avatar answered Dec 10 '22 17:12

Willem Van Onsem


You can use delattr. It will raise an AttributeError if the attribute does not exist, so you can wrap it in a method if you want:

def safe_delattr(self, attrname):
    if hasattr(self, attrname):
        delattr(self, attrname)

or use a try/except block:

try:
    delattr(self, attrname)
except AttributeError:
    pass

This has the advantage of working with classes that define __slots__, as they don't expose a __dict__ attribute.

like image 36
farsil Avatar answered Dec 10 '22 15:12

farsil