proposal: give delattr ability to ignore missing attribute

G

Gary Wilson

I would like to propose that functionality be added to delattr to
handle the case when the attribute does not exist.

First off, getattr handles this nicely with the default parameter:

value = getattr(obj, 'foo', False)

instead of:

try:
value = getattr(obj, 'foo')
except AttributeError:
value = False

or:

if hasattr(obj, 'foo'):
value = getattr(obj, 'foo')
else:
value = False


And I think it makes sense to have something similar for delattr (name
the argument as you wish):

delattr(obj, 'foo', allow_missing=True)

instead of:

try:
delattr(obj, 'foo')
except AttributeError:
pass

or:

try:
del obj.foo
except AttributeError:
pass

or:

if hasattr(obj, 'foo')
delattr(obj, 'foo')

For backwards compatibility, allow_missing would default to False.

Gary
 
L

Lie

I would like to propose that functionality be added to delattr to
handle the case when the attribute does not exist.

First off, getattr handles this nicely with the default parameter:

value = getattr(obj, 'foo', False)

instead of:

try:
    value = getattr(obj, 'foo')
except AttributeError:
    value = False

or:

if hasattr(obj, 'foo'):
    value = getattr(obj, 'foo')
else:
    value = False

And I think it makes sense to have something similar for delattr (name
the argument as you wish):

delattr(obj, 'foo', allow_missing=True)

instead of:

try:
    delattr(obj, 'foo')
except AttributeError:
    pass

or:

try:
    del obj.foo
except AttributeError:
    pass

or:

if hasattr(obj, 'foo')
    delattr(obj, 'foo')

For backwards compatibility, allow_missing would default to False.

Gary

That doesn't need to be implemented internally, you could do it
yourself in python.

def my_delattr(obj, attr):
try:
delattr(obj, attr)
except AttributeError:
pass
def my_getattr(obj, attr, default):
try:
return getattr(obj, attr)
except AttributeError:
return default
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top