[Python-ideas] setting function properties with a decorator syntax

MRAB python at mrabarnett.plus.com
Thu Mar 18 19:56:43 CET 2010


spir wrote:
> On Thu, 18 Mar 2010 00:19:40 -0700
> Chris Rebert <pyideas at rebertia.com> wrote:
> 
>> Are function attributes used *that* much?
> 
> I use them as a nice (& explicit, & clear) alternative to closures, esp. for func factories, eg:
> 
> def powerN(n):
>     def f(x):
>         return x ** f.n
>     f.n = n
>     return f
> power3 = powerN(3)
> for i in range(1,10):
>     print "%s:%s" %(i,power3(i)),
> # ==> 1:1 2:8 3:27 4:64 5:125 6:216 7:343 8:512 9:729
> 
> I find this conceptually much more satisfying than the following, since the parameter really is an attribute of the function (also, like a real upvalue, it can be explicetely updated).
> 
> def powerN(n):
>     def f(x,n=n):	# ugly ;-)
>         return x ** n
>     return f
> 
[snip]
This also works:

     def powerN(n):
         def f(x):
             return x ** n
         return f



More information about the Python-ideas mailing list