Anyone know how to define self-contained python function (but not a generator) that returns different values each time it is called ?
e.g.
def somefunc()
// define here
somefunc() # 1
somefunc() # 2
somefunc() # 3 ...
I guess we'd just need to store state somehow.
I don't think functions can rebind their variables (pass-by-value, not reference), so that's out.
Could a function that can redefine itself directly (acting on the function object)?
Here's something like javascript (state stored in attributes of function) :
def clos():
def func():
func.val += 1
return func.val
func.val = 0
return func
foo = clos()
print foo(),foo(),foo() # 1 2 3
Some other ideas; using global variable :
def redef():
global func
f = (lambda x: x)(func)
func = lambda : f()+1
return 1
func = redef
print func(),func(),func() # 1 2 3
defined as bound method on class instance :
class Foo:
def bar(self):
return 0
def baz(self):
bar = (lambda x:x)(self.bar)
self.bar = lambda : bar()+1
return self.bar()
foo = Foo()
print foo.baz(),foo.baz(),foo.baz() # 1 2 3
And as a static class method :
class Foo:
x=0
@classmethod
def baz(cls):
cls.x += 1
return cls.x
foo = (lambda x:x)(Foo)
class Foo:
pass
print foo.baz(),foo.baz(),foo.baz() # 1 2 3
Mutable (list) to store state (fudged to be able to use lambda...) :
foo = (lambda z: lambda :z.append(z[0]+1)==None and z.pop(0))([0])
print foo(),foo(),foo() # 1 2 3
Any other ideas?