Search code examples
pythonfunctionnested-function

Accessing a global function from an inner function with the same name


I have the following code:

def A():
    return 2

def B():
    def A():
        return 3

    return A()

print(B())

The result is 3 because return A() uses inner function A() of B() instead of function A(). Is it possible to call function A() (the one that return 2) inside function B()?


Solution

  • You are overriding the global A with your own local implementation. You should still be able to call the global one using the globals() trick but note that what you are doing is not good practice:

    return globals()["A"]()
    

    Update: This is not good practice because it violates multiple principles of Zen of Python, such as "Explicit is better than implicit", "Readability counts", and "If the implementation is hard to explain, it's a bad idea".