3 ms·
I thought about this. I would just avoid the need of declaring a variable with the same name as one in the enclosing scope. That means minimisation of global va
by jwdunne 9y ago
I thought about this. I would just avoid the need of declaring a variable with the same name as one in the enclosing scope. That means minimisation of global variables, minimisation of lexical pyramids, etc. Generally good things with or without explicit declarations.
If you're creating a closure, that's inherent part of the enclosing scope. Just like variable reuse is discouraged for clarity, so it should in closures.
I think declaring a global variable deep in scope sounds like recipe for hell. I think declaring a global with a name as short as you'd use in function parameters is a mistake. I don't see how it'd be a problem if you follow practices that encourage maximum clarity.
If I could see an example, it'd make it easier to understand your point - I haven't seen the problem you describe so it's difficult for me to visualise it.
- ptx 9y agoTry this: def f(): def g(): nonlocal x # change this line x = 3 print("x == {!r}".format(x)) x = 2 g() print("x == {!r}".format(x)) x = 1 f() print("x == {!r}".format(x)) It will print (because g reassigns the x in f): x == 3 x == 3 x == 1 and if you change "nonlocal" to "global", g will reassign the global x, and you get: x == 3 x == 2 x == 3 and if you remove the line entirely, the assignments will be interpreted as declaring new variables in each scope, and you get : x == 3 x == 2 x == 1
- jwdunne 9y agoI just looked up the nonlocal keyword, my python isn't strong. I'll hold my hands up - python wasn't a good example here. I was under the impression you could use and mutate outer scope variable.