![]() |
| Python Closures and Scope - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Python Closures and Scope (/thread-31467.html) |
Python Closures and Scope - muzikman - Dec-13-2020 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 RE: Python Closures and Scope - bowlofred - Dec-13-2020 They're necessary if you want to modify an outer scope variable. They're not necessary if you only want to access the variable. RE: Python Closures and Scope - muzikman - Dec-14-2020 Yeah, I figured. :) Thanks. |