[Python-ideas] Syntax for defining parametric decorators
Nick Coghlan
ncoghlan at gmail.com
Mon Jul 9 03:46:16 CEST 2012
On Mon, Jul 9, 2012 at 11:11 AM, Mike Graham <mikegraham at gmail.com> wrote:
> On Sun, Jul 8, 2012 at 6:54 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> Beyond that, no, this is too limited - it only helps when there's no extra
>> code in the outer scope which, in my experience, is the exception rather
>> than the rule.
>
> I'm not sure I think that's the case.
- functools.wraps
Not really, as it uses functools.partial, not a nested def (sure you
could rewrite it to use a nested def instead, but why?)
> functools.lru_cache
No, as it has pre- and post-processing steps around the nested
function definition.
- reprlib.recursive_repr
Yes, this one would qualify.
However, the simplest possible complete definition of decorators is as follows:
- a decorator expression (the bit after "@") on a def statement must
produce a function decorator
- a decorator expression on a class statement must produce a class decorator
- a function decorator accepts a function and produces another object.
This is typically another function (or even the original function for
annotation and registration decorators), but may also be a different
kind of object such as a descriptor (e.g. property, classmethod,
staticmethod) or context manager (e.g. contextlib.contextmanager)
- a class decorator is similar, but accepts a class rather than a function
- a decorator factory is any callable that returns a decorator
- function decorators are often written as functions that return a
nested function (1 level of lexical nesting)
- function decorator factories are often written as functions that
return a function that returns a functions (2 levels of lexical
nesting)
Creating a dedicated syntax for the special case of function decorator
factories written to use lexical nesting makes the language as a whole
*more* complicated rather than less. The only way to actually make
them *simpler* would be to eliminate one or more of the bullet points
from the above list, and that can't be done while retaining the
current functionality.
Yes, it means that to write efficient custom decorator factories you
need to understand both the decoration process and lexical closures.
That's *OK* - it just means writing custom decorator factories (as
opposed to using those written by others) is a moderately advanced
metaprogramming technique (it's still a lot simpler than writing a
custom metaclass, though).
Some concepts are just hard to get your head around, but that doesn't
mean we should be creating dedicated syntax for a very specialised use
case.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list