Decorators, Identity functions and execution...

Fredrik Lundh fredrik at pythonware.com
Sun Apr 9 10:50:56 EDT 2006


Chance Ginger wrote:

> It isn't a syntax error...I tried it before I posted. In fact
> def t(x) :
> def I(x) : return x
> return I
>
> is correct.

tabs don't make it through all channels.  don't use tabs for
indentation when you post to newsgroups or mailing lists.

and @(Y) is not valid Python syntax.  no amount of indentation
will change that.

> Decorators are a way to add "syntactic" sugar to Python,
> extending it in ways that make it useful for tools.

that's a rather narrow view of what a decorator does, and doesn't
help much in understanding how they work.

which is unfortunate, because it's very simple: decorators are simply
ordinary callables, and the result of the decoration is whatever the
callable returns.

in fact, any callable can be used to decorate a function:

    >>> @str
    ... def foo(bar):
    ...     pass
    ...
    >>> foo
    '<function foo at 0x00986730>'
    >>> foo("bar")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: 'str' object is not callable

and it's all done at runtime; there is no magic involved whatsoever.

    >>> @open
    ... @str
    ... def bar(foo):
    ...     pass
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    IOError: [Errno 2] No such file or directory: '<function bar at 0x009867F0>'

> I am trying to do is lessen the impact on the time used in
> executing Python code when I use some forms of decorators.

if you don't want Python to execute some code, all you have to do is
to make sure that it isn't called.

</F>






More information about the Python-list mailing list