Decorators, Identity functions and execution...

Chance Ginger cginboston at hotmail.com
Sun Apr 9 06:50:24 EDT 2006


On Sun, 09 Apr 2006 09:51:18 +0200, Fredrik Lundh wrote:

> Chance Ginger" wrote:
> 
>> If I define a decorator like:
>>
>> def t(x) :
>> def I(x) : return x
>> return I
> 
> ... you get a syntax error.
> 

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.

>> and use it like:
>>
>> @t(X)
>> def foo(a) :
>> # definition of foo...
>> pass
> 
> that's also a syntax error.

Once again this isn't an error assuming you pass in a valid 'X'.


> 
>> or maybe this:
>>
>> @t(X)
>> @(Y)
>> def bar(a) :
>> # The definition of bar...
> 
> and that's not even fixable.
>

Again you are mistaken. If I say:

@t(1)
@t(2)
def bar(a) : pass

It is perfectly valid. 
>> Will in encounter much of a penalty in executing
>> 'foo' or 'bar'?
> 
> since foo is wrapped, calling foo will call your I function, which in
> turn calls the original foo.
> 
>> If so, is there a way to define t such that Python knows it is
>> the identity function and short-circuit evaluation?
> 
> if you don't want to wrap something, don't wrap it:
> 
>     def t(x) :
>         def I(x) :
>             return x
>         if date == friday:
>             return x # don't wrap it
>         return I # wrap it
> 
> </F>

Decorators are a way to add "syntactic" sugar to Python,
extending it in ways that make it useful for tools. What 
I am trying to do is lessen the impact on the time used
in executing Python code when I use some forms of decorators.



More information about the Python-list mailing list