Reputation: 61
I currently have an object passed to my callback which is a dictionary and which I have to return.
The invoker called obj.setdefault("Server", "Something")
on the dictionary so that it has a default value even if the key/value pair does not exist.
How can I revert/remove that setdefault
(remove the default value)? I mean I simply don't want that key/value pair in the dict and it seems that it doesn't have complications if the key doesn't exit, but it is always added because of the default.
Upvotes: 2
Views: 442
Reputation: 74
Assuming the value is not in the dictionary when passed to the callback, dict.setdefault
is not really the problem - this operation is one of many available for changing a python dictionary. Specifically, it ensures SOMETHING is stored for the given key, which can be done directly anyway with an indexed assignment. As long as your code and the invoker are both maintaining a reference to the same dictionary, you have no real choice but to trust the invoker (and any all other reference holders to this dictionary).
The mutability of the dictionary is the problem, so the possible solutions orient around the leeway in the design. I can only think of:
Upvotes: 0
Reputation: 54561
The setdefault
method sets the value of the Server
key to Something
(as long as the Server
key is not already in the dictionary). You can simply delete the Server
key from the dictionary:
if 'Server' in obj: del obj['Server']
If you don't want to remove the server key when its value is different from Something
, do:
if obj['Server'] == 'Something': del obj['Server']
However, you cannot tell whether the value of Server
was added to the dictionary as a default value or as a plain setting of a key-value pair. That's because after invoking setdefault
, the dictionary holds the key-value pair without any indication as to how it was added.
Demonstration:
>>>d = {}
>>>d.setdefault("Server", "Something")
>>>d
{'Server': 'Something'}
>>>del d['Server']
>>>d
{}
Upvotes: 5