0

If I have an outer function returning an inner function like so:

def outer():
    outer_var = 1

    def inner():
        return outer_var

    outer_var = 2
    return inner

Calling outer()() will return 2. However, I want the inner function to return the value outer_var had when the inner function was created, not when it was called.

The only solution I could come up with was:

def outer():
    outer_var = 1

    def inner(inner_var=outer_var):
        return inner_var

    outer_var = 2
    return inner

Calling outer()() will now return 1. Is there a better solution that doesn't need kwargs? I don't think it's necessary to mention that in my actual code outer_var will only be known at runtime.

uzumaki
  • 1,743
  • 17
  • 32

1 Answers1

1

I was going to suggest this:

def outer():
    outer_var = 1

    temp_outer_var = outer_var
    def inner():
        return temp_outer_var

    outer_var = 2
    return inner

But your solution is more elegant!

No

I don't think there is a more elegant solution than these.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • Well in my case I create callback functions inside a loop, so assigning to a different variable won't help as the variable will change in every iteration. – uzumaki Mar 20 '23 at 20:38