Apparently, python will look up to the module scope for reading the value of a variable, but not for the setting of it, which is ugly behavior in my opinion.
I disagree. Every scoping mechanism I'm familiar with allows nested scopes to read parent scopes with ease, while writing to parent scopes varies. While not consistent, not requiring the global keyword on a read works for the common usage.
Python has an issue with scoping due to being dynamic. In C#, if I wanted to local x to over-rule global x in my method, I'd have to declare it:
class Foo
{
int x = 5;
private Bar()
{
int x = 20;
}
}
Whereas in Python...
x = 20
def bar():
x = 10 // global x? Or local scoped x?
It's a design trade-off. I think that by making the edge cases (I want to write to module scope) the odd ones out, and making the common cases (reading from module scope) work as you'd expect, Python does a reasonable job of not surprising you and not getting in your way.
View all comments
Show parent comment
3
u/[deleted] Apr 11 '08
I disagree. Every scoping mechanism I'm familiar with allows nested scopes to read parent scopes with ease, while writing to parent scopes varies. While not consistent, not requiring the global keyword on a read works for the common usage.
Python has an issue with scoping due to being dynamic. In C#, if I wanted to local x to over-rule global x in my method, I'd have to declare it:
Whereas in Python...
It's a design trade-off. I think that by making the edge cases (I want to write to module scope) the odd ones out, and making the common cases (reading from module scope) work as you'd expect, Python does a reasonable job of not surprising you and not getting in your way.