0

I have a nested function outer_func

  • Outer function creates a dict: _dict and return inner function inner_func
  • Inner function will accept key and value, store them into _dict and print all the local variables
  • inner_func will be returned by outer_func and called globally
def outer_func():

    _dict = {}

    def inner_func(k,v):
        _dict[k] = v
        print(locals())
        
    return inner_func


ifunc = outer_func()
ifunc('a',3)
ifunc('b',4)

The outputs would be:

# {'v': 3, 'k': 'a', '_dict': {'a': 3}}
# {'v': 4, 'k': 'b', '_dict': {'a': 3, 'b': 4}}

We can see that local variable _dict changed each time the ifunc was called.

I would thought that local variable _dict would be deleted once the outer_func return the inner_func which apprently not happen.

What did I miss here?

petezurich
  • 9,280
  • 9
  • 43
  • 57
IMAPOTATO
  • 31
  • 3

0 Answers0