by ramnes · 8y ago · 0 comments
I completely agree in that saying "a decorator is a function that takes a function and returns a function" isn't technically correct since you can do much more than just that; but for readability, maintainability and other real world purposes, you might want to keep to that definition.
Annotation, registration, dispatch and verification are pretty much the most common uses for decorators. If using decorators for these is bad, then decorators aren't needed at all: function wrapping is much more rarely used than those other four, and would not warrant an additional syntax construct.
What I dislike are mostly the inputs 8, 9, 13, 14, and 23 that could give nasty ideas to an inexperienced developer, while a more experienced developer wouldn't need them to understand that a decorator is just a syntactic sugar and that, yes, "applying a decorator d to a function x [is] the same as writing the definition of x, then x = d(x)" (which the author seems to refute).
I understand that those examples are solely intended to show that "it works", but they aren't educational to me.
"Decorators for preconditions" look pretty neat as well. It's a little sad that the preconditions themselves have to be written inside strings though.
Isn’t it possible to pass a lambda instead?
In fact, you could define a number of useful precondition functions in a single module and use them throughout a project. A couple of higher-order functions could make the post's examples safer and nicer-looking too. For example:
@precondition(starts_with('The year is '))
where the starts_with precondition is: def starts_with(param):
def test(s):
return s.startswith(param)
return testCan you elaborate on that, please?
Considering the examples given by the author, I think they would be a better option.