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

spir denis.spir at gmail.com
Thu Mar 18 19:32:05 CET 2010


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




More information about the Python-ideas mailing list