Python Forum

Full Version: Python Closures and Scope
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I don't like how Python handles scope. Inner functions cannot access the outer function's variables when in any other language, they can. Here is an example closure in which I had to use the nonlocal keyword in order to have access to the outer functions variable of the same name. The global, function and block namespaces should be automatic. Keywords like Global and nonlocal; are they really necessary?

def my_func():

    count = 0
    def inner_func():
        nonlocal count
        count += 1
        return count

    return inner_func

a = my_func()
print(a())
print(a())
print(a())
OUTPUT:
1
2
3
They're necessary if you want to modify an outer scope variable. They're not necessary if you only want to access the variable.
Yeah, I figured. :) Thanks.