4 ms·
Terrible example, because he is writing the keys when calling the functions: mydict[“foobar”]() is basically a worse version of using a module mymod.foob
by nomdep 3y ago
Terrible example, because he is writing the keys when calling the functions:
mydict[“foobar”]()
is basically a worse version of using a module
mymod.foobar()
The REAL value of this pattern is when the keys are going to change on runtime:
for name in userfilters:
im = filtersdict[name](im)
- zerojames 3y agoLove this! Thank you for sharing (I'm the author).
- sanderjd 3y agoWhat is value are you envisioning is associated with the dynamic `name` key in your example? In my mind, this is more a case where I might return an anonymous function that captures the name, but it's less clear to me what the dict is for.
- lijok 3y agoEven when key change at runtime, wouldn't you use getattr on a module? for name in userfilters: filter_function = getattr(mymod, name, None) if filter_function is None: raise NotImplementedError(name) im = filter_function(im)
- Izkata 3y ago> The REAL value of this pattern is when the keys are going to change on runtime Which is demonstrated in the article, see second example (third and fourth code blocks).
- MaxBarraclough 3y agoEven when changes are going on at runtime, strings are rarely the right answer. There's a name for when this approach is taken so far as to become an antipattern: stringly typed programming. [0] Typically, enums should be used in place of the way strings are used in the post. The obvious advantages of enums: they use language-level identifiers, so the language is able to check whether you're referring to something that exists. IDE autocompletion will work properly, so you won't have to memorise which strings are accepted where. Enums can also nicely leverage a static type system in languages that support it (i.e. it should be a compile-time error to try to use a member value from an irrelevant enum). Dispatching over an enum may also have performance benefits, if that matters. That said the post does mention that the strings-as-keys approach is particularly useful in hand-written parsers, which sounds like a reasonable exception. [0] https://blog.codinghorror.com/new-programming-jargon/ https://blog.codinghorror.com/new-programming-jargon/