Python handles globals badly.

Chris Angelico rosuav at
Thu Sep 3 16:03:49 CEST 2015

On Thu, Sep 3, 2015 at 11:22 PM,  <tdev at> wrote:
> Sample "Good":
> module A
>    _x = 0
>    def y():
>         _x=1
> why - this I have tried and try to explain in my and your posts
>       in the hope a PEP will arise which frees me and hopefully
>       a lot other developers getting forced to use "global"
>       (If developers need this "global" - ok, but I and
>         hopefully more want not to be forced with that
>         code-contaminator, especially having a lot more vars)

Okay. Let's suppose that some magic is worked out that makes this
work. Now let's try this example:

def x(q):
    for word in generate_words():
        if word.matches(q):
            return word

def y():
    word = x("blue")
    otherword = x("green")
    if word < otherword: return otherword
    return x("red")

How would you reason about this code? Would you not expect that the
instances of 'word' in each function are completely independent? (And
while this is a contrived example, the exact same thing happens *a
lot*, where the name used in a "return" statement is the same as the
name that thing gets assigned to. After all, if it's a logical name
for that thing in one place, it's likely a logical name in the other,
too.) According to your proposal, they would cease to be independent
if the module grows an attribute 'word'. Since, in Python, such
attributes can be injected from outside, there is literally no way to
reason about this code in isolation. That makes it very difficult to
track down problems.

Definitely do not like this.


More information about the Python-list mailing list