Wildemar Wildenburger said:
I guess the first one could be useful if you want to compare two data
structures but prune part of the structure in the comparison (e.g. in a
unit test assertion). So not forgetting that this only works when the
wildcard is on the left of the comparison:
def __eq__(self, other):
return True
dontcare = DontCareClass()
[1, dontcare, 3]==[1, 2, 3] True
[1, dontcare, 3]==[1, 4, 3] True
[1, dontcare, 3]==[1, 4, 2]
False
I think for more general use though it's a non-starter. If Python had it
builtin it should compare equal in *all* situations and what on earth
should aDict[dontcare] do?
I can think of one use for a black hole function, but it is very specific.
It would be kind of nice to have a variation on 'super' which traps
AttributeError and returns the black hole instead, or perhaps just an
optional third argument for a default to return (c.f. dict.get). So you
could write:
class C(object):
def method(self, arg):
super(C, self, blackhole).method(arg)
... whatever ...
and method would call any base class definition of method but not care if
there isn't one. The alternative to this is either to catch and ignore the
exception (which is a pain), or better to create a dummy base class which
implements the interface but doesn't propagate the calls.
I suppose the same argument could be made for any pattern of calling the
result of getattr when the attribute might not exist. Replace:
m = getattr(obj, key, None)
if m is not None:
m(something)
or:
if hasattr(obj, 'somekey'):
obj.somekey(whatever)
with:
getattr(obj, key, blackhole)(something)
The catch here is that the current pattern often has an 'else' clause as
well and you can't replace those ones with blackhole.