In Python the dict object has a "pop" method which returns and removes a key from a dict, with an optional default if the key doesn't exist.
What is the best way to do this for general object attributes?
I'm thinking:
my_obj.__dict__.pop('key_name', default)
Should be a good option but I'm worried that directly muting the object's dict might have unintended side effects that I'm not aware of. Is there a better option?
The pop() method removes the specified item from the dictionary. The value of the removed item is the return value of the pop() method, see example below.
The "AttributeError: 'str' object has no attribute 'pop'" occurs when we try to call the pop() method on a string instead of a list. To solve the error, call the pop() method on a list or use the rsplit() method if you need to remove the last word from a string.
(for objects with a __dict__
) "popping" an attribute is the same thing as popping it from the __dict__
, and therefor your suggested implementation is correct.
EDIT: @Erik correctly pointed out that using __dict__.pop
can raise a KeyError
, where the apporpriate exception is an AttributeError
. So a better implementation would add try/catch/reraise-as-AttributeError.
I would just point out that what you're trying to do is "popping" an attribute of an object, not a key.
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