Why can't Python access the subfunction from the outside?

def A(): def B(): #do something a = A() aB() 

Why is there no such (such simple code) in Python? Is there a "pythonic" (legible, unsurprising, not hacky) workaround that doesn't turn A () into a class?

Edit 1: It was explained above that B is local to A, so it exists only if A is evaluated. Therefore, if we make it global (and we won’t forget it), then why doesn’t it work?

 def A(): def B(): #do something return A() a = A() aB() 

It says that it returns a "NoneType" object.

+6
source share
2 answers

Because the function definition just creates a name in the local namespace. What you do is no different from:

 def f(): a = 2 

and then ask why you cannot access a from outside the function. Names associated within a function are local to the function.

Also, your suggested code is weird. when you do a = f() , you set the return value of the function. Your function does not return anything, so you cannot access anything through the return value. You can directly return the internal function:

 def f(): def g(): return "blah" return g >>> func = f() >>> func() 'blah' 

And it really can be useful. But there is no general way to access things inside a function from outside, except by changing global variables (usually a bad idea) or returning values. This is how functions work: they accept input and return results; they do not make their insides accessible to the external word.

+7
source

To call B with the desired syntax, use:

 def A(): def B(): print("I'm B") AB = B return A a = A() aB() AB() 
+5
source

Source: https://habr.com/ru/post/927075/


All Articles