[Python-ideas] setting function properties with a decorator syntax
Jim Jewett
jimjjewett at gmail.com
Fri Mar 19 15:57:42 CET 2010
For anyone finding this on a later search, note that he still uses a
closure; just a slightly neater one.
Within a function, there is no way to refer to the function itself,
except by name -- and that name may well have been reassigned to
something else. A more local enclosure protects against that
reassignment.
-jJ
On 3/18/10, spir <denis.spir at gmail.com> 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
>
> (Let us use the opportunity that python funcs are real objects :-)
>
> A "parameterisable" generator factory:
>
> def powers(n, start=1, stop=None):
> def f():
> while True:
> f.i += 1
> if f.stop and f.i >= f.stop:
> raise StopIteration
> yield (f.i, f.i ** f.n)
> f.n = n
> f.i = start-1
> f.stop = stop
> return f
> for (i,x) in powers(3, 1,10)():
> print "%s:%s" %(i,x),
> # ==> 1:1 2:8 3:27 4:64 5:125 6:216 7:343 8:512 9:729
>
>
> Denis
> ________________________________
>
> vit e estrany
>
> spir.wikidot.com
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
More information about the Python-ideas
mailing list