d = {Foo : do_something_with_foo,
Bar : do_something_with_bar}
d.get(type(x), default_function)(x)
Probably some more efficient way but honestly I've used this before instead of writing a whole if elif chain.--edit--
Makes python's lack of a switch operator sometimes less painful...
I guess my uses for dictionaries are pretty vanilla. But that’s a kind of thing I do all the time. I set up dictionaries where the key is a possible value from some operation or query, and the value is the function I want to perform on that value.
This extends that concept. Thanks!
- If the objects are value types (as dataclasses are, since they respect equality): it makes sense to use them as dict keys, just as it makes sense to use tuples as dict keys. Changing a tuple to a namedtuple is natural.
- If the objects have reference semantics rather than value semantics, you can still use them as dict keys in Python. The default __hash__ is the id/address of the object (the default __eq__ uses id() too). I don't particularly like this style but I have seen it used. It feels error-prone to me and not "algebraic".
I've used tuples has dict keys several times, so I don't see why I conceivably wouldn't use a Data Class containing the same data as a dict key.