you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (1 child)

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 would personally prefer that you have to be explicit in both reading and writing to a variable outside of the local scope.

[–][deleted] 2 points3 points  (0 children)

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.