0

How does Python decide which vars to enclose? You can see when a variable is defined as a name, it is happily closed, but when defined using locals(), it is not closed.

Works great:

def outer():
    x = 5
    print(x)
    def inner():
        return x
    return inner()


print(outer())

Doesn't work:

def outer():
    locals()['x'] = 5
    print(locals()['x'])
    def inner():
        return locals()['x']
    return inner()
print(outer())
martineau
  • 119,623
  • 25
  • 170
  • 301
Carbon
  • 3,828
  • 3
  • 24
  • 51
  • I guess in inner locals has only things local to inner, and x is available otherwise in the scope. So that return x would work in latter version too. – antont Sep 18 '20 at 17:00
  • Check out this answer: https://stackoverflow.com/a/32221772/10302746 – Lev M. Sep 18 '20 at 17:08
  • Ah, ok, so it searches what exists in the outer scope at time of creation? – Carbon Sep 18 '20 at 17:19
  • Well, for starters, `locals()['x']` *doesn't even create a local variable*. But in any case, closures are created when the function is *compiled*. – juanpa.arrivillaga Sep 18 '20 at 17:19

0 Answers0