
On Thu, Apr 28, 2022 at 01:18:09AM -0000, zmvictor@gmail.com wrote:
*Background* It is frequently desirable to delete a dictionary entry if the key exists.
Frequently? I don't think I've ever needed to do that. Can you give an example of real code that does this?
It is necessary to check that the key exists or, alternatively, handle a KeyError: for, where `d` is a `dict`, and `k` is a valid hashable key, `del d[k]` raises KeyError if `k` does not exist.
The simplest one-liner to delete a key if and only if it exists is with the `pop` method: mydict.pop(key, None) # Ignore the return result. That may not be the most efficient way. I expect that the most efficient way will depend on whether the key is more likely to exist or not: # Not benchmarked, so take my predictions with a pinch of salt. # Probably fastest if the key is usually present. try: del mydict[key] except KeyError: pass # Probably fastest if the key is usually absent. if key in mydict: del mydict[key] So we already have three ways to delete only an existing key from a dict, "optimised" (in some sense) for three scenarios: - key expected to be present; - key expected to be absent; - for convenience (one-liner). With three existing solutions to this problem, it is unlikely that a fourth solution will be blessed by building it into the dict type itself. (Although of course you can add it to your own subclasses.) Especially not when that solution is easily mistaken for something else: d -= 1 # Are we subtracting 1, or deleting key 1? Alone, that is not a fatal problem, but given that there are three other satisfactory solutions to the task of deleting an existing key, even minor or trivial problems push the cost:benefit ratio into the negative. By the way:
class DemoDict(dict): def __init__(self, obj): super().__init__(obj)
If the only purpose of a method is to call super and inherit from its parent class(es), as in the above, then you don't need to define the method at all. Just leave it out, and the parent's `__init__` will be called. -- Steve