Search code examples
pythonscopemetaprogramming

Changing reference to an outer function


def foo():
    print(True)


def bar():
    foo()


def baz():
    def foo():
        print(False)

    foo()
    bar()


baz()

Outputs:

False
True

I need to make it output:

False
False  

By making bar call foo defined inside of baz without touching anything outside of baz itself.


Solution

  • for this, you need to overwrite foo's definition in the global scope. Just use the global keywbord:

    def foo():
        print(True)
    
    def bar():
        foo()
    
    def baz():
        global foo
    
        old_foo = foo # if you want to backup the original definition of foo (optional)
    
        def foo():
            print(False)
    
        foo()
        bar()
    
        foo = old_foo # revert foo to its original state (optional)
    
        baz()
    

    Output:

    False
    False