henneray
henneray

Reputation: 449

Assign global variable to a function's local variable

I want to loop over some global variable i and each time compile a new function that uses the instantaneous value of i. I can then use each of these functions in future, independent of the current value of i.

The problem is I can't find a good way to make the global variable i stay local within the namespace of the function. For example:

i = 0

def f():
    return i

i = 1

print(f()) #Prints 1, when I want 0

I found one solution but it seems very clumsy:

i = 0

def g(x):
    def h():
        return x
    return h

f = g(i)
i = 1

print(f()) #Prints 0 as I wanted.

Is there a better way to do this, maybe some kind of decorator?

Upvotes: 0

Views: 37

Answers (1)

Jacques Gaudin
Jacques Gaudin

Reputation: 16958

Python functions are objects, you can set an attribute on them:

i = 0

def f():
    return f.i

f.i = i

i = 1

print(f()) # Prints 0 as you wanted

or:

for i in range(5):
    f.i = i
    print(f())

Note that an argument would do the same.

Upvotes: 1

Related Questions