def once(fcn):
func = [fcn]
def inner(*args):
return func.pop()(*args) if len(func) else None
return inner
def add(a,b):
return a+b
oneAddition = once(add)
print(oneAddition(2,2)) # 4
print(oneAddition(2,2)) # None
print(oneAddition(12,200)) # None
print(once(add)(2,2)) # 4
print(once(add)(2,2)) # Should return None, returns 4
print(once(add)(12,200)) # Should return None, returns 212
So the purpose of this nested function is to keep track of how many times the outer has been called. It returns the result of add only the first time that it is being called. After that, whenever it's called it returns None.
What really piqued my interest is that oneAddition=once(add)->oneAddition(2,2) and once(add)(x,y) behave differently.
In the second method, it seems that the outer function is executed as well. With the first method, the outer function is only executed upon the construction (much like decorators).
Can someone explain to me why that is? Thanks very much.
P.S. I know that using nonlocal vars would be a much more appropriate solution, I just included the function-in-a-list approach because it looks quite cool (found it online).