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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With