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.
source share