3 ms·
Yes, it is syntactic sugar for composition. It exists to make source code more self-documenting because you can see that a function is "decorated" at the point
by stevejohnson 17y ago
Yes, it is syntactic sugar for composition. It exists to make source code more self-documenting because you can see that a function is "decorated" at the point of its definition, rather than some other location where the conceptual context is lost.
The best common use case I can think of for it is web interfaces with access control:
@login_required
def profile(...):
#...
@admin_required
def ban_user(...):
#...
Decorators have also been used for great justice in unit testing frameworks and GUI libraries.
Your example does look a little overzealous, which is why people don't normally use decorators in that way. Usually you'll only see one decorator per function.
- silentbicycle 17y ago> at the point of its definition Ok, that makes sense, thanks. I guess needing syntax for this is a consequence of Python's quirky lambdas. In languages with full lambdas, you can just wrap an anonymous function at the point of definition. profile = login_required(function (...) ...) -- in Lua (define profile (login-required (lambda (...) ...))) ; in Scheme let profile = login_required(fun ... -> ...) (* in OCaml *) Putting the decorator on its own line draws attention to it, though. This is probably also another instance of Python's "flat is better than nested" design choice.