0

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?

1
  • 1
    Something doesn't sound quite right. It might require redesigning the solution. Commented Jun 6, 2018 at 16:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That's a nice idea, but it doesn't quite work in my context. If I were to now append f to some list each time within a loop and then execute any member of the list at a later point, I just get the latest definition of f again.
Take no offence but it sounds like there is a flaw in the design. It sounds very complicated!
Just as tip: putting functions in a list is rare in Python. One of the beauty of this language is mapping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.