create dynamic functions keeping state

96 views Asked by At

Python beginner question. Say you want to dynamically create a function that keeps some state (in the code below an integer i). Then as the function defined is an object, we could use it later on. In the following code, I add the functions to a list, and each call to print(fn(0)) should result in 0 1 2 3 4, but instead I get 4 4 4 4 4 as if only the latest value of i is used.

fns = []
for i in range(5):

    def fn(x):
        return x + i

    fns += [fn]
print(fns)

for fn in fns:
    print(fn(0))
quit()

Is it possible to accomplish in Python what this code tries to do?

2

There are 2 answers

2
falsetru On BEST ANSWER

To work around the late binding issue, you can use default keyword parameter:

for i in range(5):
    def fn(x, i=i):  # <-----
        return x + i
    ....
1
sentiao On

A function that retains its own state? I would do it like this:

class func:
    # can behave as a function, but can also hold its own value
    def __init__(self, value=0):
        self.value = value

    # this function is the actual 'function' that is called each time
    def __call__(self, arg): 
        self.value += arg
        return self.value

fns = []
for i in range(5):

    # create new function, and give it a starting value of  i
    fn = func(i)

    fns += [fn]


for fn in fns:
    print( fn(0) )

The result is 0 1 2 3 4