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) 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)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.
for name in userfilters:
filter_function = getattr(mymod, name, None)
if filter_function is None:
raise NotImplementedError(name)
im = filter_function(im)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.
Which is demonstrated in the article, see second example (third and fourth code blocks).