Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement attribute pop in python

Tags:

python

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?

like image 922
galarant Avatar asked Oct 23 '13 19:10

galarant


People also ask

What does pop in Python?

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.

How do you pop a string to an object in Python?

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.


1 Answers

(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.

like image 102
shx2 Avatar answered Sep 21 '22 01:09

shx2