Python: How can a closure continue its existence after the outer function is reassigned?

Viewed 567

I learning about closures in Python, and I get the concept well enough. While messing around in IDLE I thought about what would happen if I reassigned the enclosing function and then tried to call the enclosed function:

>>> def outer_function(hello):
        message = hello
        def inner_function():
            print(message)
        return inner_function

>>> function = outer_function("hello")

>>> function()
hello

>>> def outer_function():
    print("hi")

>>> function()
hello

I think that this is very interesting, but I realize that I do not have a good enough understanding about what happens to the closure in memory etc. Can someone explain how I can call inner_function after reassignment of outer_function?

2 Answers
Related