Extended Syntax for Decorators
Learn about extended syntax for decorators.
We'll cover the following
Python 3.9 introduced a novelty for decorators with PEP-614, because a more general grammar is allowed. Before this enhancement, the syntax for invoking decorators (after the @
) was restricted to very limited expressions, and not every single Python expression was allowed.
Writing complex expressions
With these restrictions lifted, we can now write more complex expressions and use them in our decorators, if we think that can save us some lines of code (but as always, be careful not to overcomplicate and get more compact but much harder-to-read lines).
Example
As an example, we can simplify some of the nested functions we typically have for a simple decorator that logs a function call along with its parameters. Here (and for illustration purposes only), we've replaced the nested function definitions, typical of decorators, with two lambda expressions:
Get hands-on with 1400+ tech skills courses.