2 ms·
Dynamic dispatching comes to mind. d = {Foo : do_something_with_foo, Bar : do_something_with_bar} d.get(type(x), default_function)(x) Probably som
by UncleEntity 9y ago
Dynamic dispatching comes to mind.
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...
- ianamartin 9y agoOh, that makes sense. Not sure why this question rubbed people the wrong way. I was genuinely curious about when you would use an object as a key. 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!