45 points · by zerojames · 3y ago · 56 comments
The article talks about string keys, but Python allows many things to be used as keys. For example, instead of chains of `elif` we can look up `True` in a dictionary:
>>> age = 25
>>> {
... (age < 18): "Forbidden",
... (age == 18): "OK, you're old enough now",
... (age > 18 and age < 20): "LOL teen emoji amirite?",
... (age >= 20 and age < 40): "Hi",
... (age >= 40): "Welcome",
... }[True]
'Hi'
One thing that's annoying with this pattern is that Python calculates values eagerly, so we can't use it for expensive calculations or observable effects. To make the values lazy we can wrap them in `lambda:`, but at that point we're essentially re-implementing dynamic dispatch, so classes may be better (or a couple of `elif`s, at most). Note: that's what the article's doing ;)The two are not so easily translatable I guess, considering further conditions usually have the built-in assumption that all preceding conditions were evaluated to false.
I think when I picked my major, I never understood what software engineering is, or even what engineering is. Honestly I shouldn't be complaining. So many people have it worse.
Coding would still be fun if it weren't a job, where we bend tech backwards to please the users (instead of teaching users to do the right thing)
In Python you can write this more concisely as:
(18 < age < 20)
If you support Python 3.10+ you can do this far more cleanly.
Also, Python requires explicit returns (unless we're in a lambda), so using a `match` statement for the above example would need multiple duplicate statements (either `return`, or assignment to a repeated variable name, or calling a repeated continuation (although that's less common, due to Python not eliminating tail calls), etc.). A chain of `elif` would also have that problem.
I suppose the condition coming first is nice
Of course if you're trying to do a registry-pattern style thing the constraints are different (though there I also think that you end up wanting to base your stuff on classes whose metaclass registers itself based on a string-y class attr or something...)
Though in the end it's super dependent on what kind of code you're trying to write. No rule is absolute, especially in this category of aesthetics.
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).
class Registry:
constructors = {}
@classmethod
def register(cls, other):
# you can do it by an implicit property or the class name in simple cases. It's better not to use implementation details here, eg you should use an explicit class attribute
# you can also verify that the other class holds certain invariants here, so it fails immediately
cls.constructors[other.__name__] = other
# cls.contructors[other.name] = other
@classmethod
def from_name(cls, name):
# error handling code here
return cls.constructors[name]
# in something.py
@Registry.register
class Something:
def __init__(self, foo, bar=None):
self.foo = foo
self.bar = None
# In something_test.py
import something
import registry
smth = registry.from_name("Something")
s = smth('foo', bar=2)
You'll want to have a registry for each base class (they largely all look the same except for the invariant checks), but this way you don't have to update a map, you just add the decorator to new classes as you build them. It also allows classes to be completely unaware of the registry and focus on their actual task.Additionally, the invariant checking can do all sorts of things that you can't do with a base class, eg making sure that overridden properties are still properties, checking that class attributes follow whatever formatting convention you have, etc etc
How is this better than just functions in a module? (import the module as math_exprs, use getattr)
I don’t mean to poo poo on it. I really do like learning new patterns, but I haven’t yet grasped this one’s utility.
You can also list the registered function with math_exprs.keys() and that might not be as easy with a module either.
I don't think it makes much sense in the example code given
I'm pretty sure it's bad practice but in one project i needed some form of parameterised extensibility (parsing a broad mix of files onto a standard format). So what i did was have other devs subclass an abstract base class I created (with some predefined attributes and methods to fill in) and then generated my execution dictionary based on the attributes of the subclasses of the base class.
But if the keys are known statically (as in the article), I think it's generally better to use named functions.
But it's good to be aware of the capability, for cases like you're describing.
funcs = {}
def register(key):
def decorator(func):
funcs[key] = func
return func
return decorator
@register("some_data_key")
def do_something_with_some_value(value):
return value
# later....
def parse(data):
return {
key: func(data.get(key)) for key, func in funcs.items()
} const case = 'case1'
const result = {
'case1': 'value1',
'case2': 'value2',
'case3': 'value3',
'case4': 'value4',
} [case] || 'defaultVal'"When your OOP support sucks so bad, the people might as well just use maps."
But I understand that this is a very python answer.
1. It is not static. It can be configured, changed at runtime, etc
2. First order functions are very powerful as well
The real difference is that since it's not an object, "self" isn't in the function signature which to be fair can be annoying for a collection of stateless functions. So this is actually closer to a module.
I agree with (2), but I'm not sure the pattern from the OP is a good example of using that power. It seems like using a language feature - mapping a string to an anonymous function - when a better one exists: defining named functions. Named functions can be looked up dynamically by name in python, and are (I think) generally more clear to a reader, especially with the standard documentation and type hints.
Edit: I don't believe this is any slower, actually. It may even be marginally faster than a class, since a class adds some QOL features that will add a little overhead that would add a few branches to the code path.
But if you're worried about speed, don't use Python anyways.
SUPPORTED_INFERENCE_MODELS = {
"groundingdino": registry.grounding_dino_base,
"yolov8": registry.yolov8_bas,
...
}https://blog.roboflow.com/whats-new-in-yolov8/
In one example, dictionary dispatch decides what model to use: YOLOv5, v8, SAM, and others.