2

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()?

Selcuk
  • 57,004
  • 12
  • 102
  • 110

1 Answers1

4

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".

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • @tdelaney I was trying out nested function and suddenly this question came into my mind. Ofc, I know that this is a bad practice. – Vinh Quang Tran Sep 10 '21 at 02:09
  • @VinhQuangTran- it isn't necessarily bad practice to use `globals()` to access variables at module scope. It seems odd in your example, but then its just a trivial test program. – tdelaney Sep 10 '21 at 02:11
  • @tdelaney Correct, I elaborated it a little more in my edit. What is bad practice is not the use of `globals()` but to override global names with locals, leading to unexpected and hard-to-find bugs. – Selcuk Sep 10 '21 at 02:12