Not to generate local variable when only "+=" operator's found

Summary

When “=” operation found in function definition code, Python adds the variable name to this function’s local variable list - this is easy for me to understand; but “+=” was treated the same way - different from what people (beginners like me) would expect.

Example

When people do

global_var = 0

def access():
        print(global_var)
        global_var += 1

access()

You can tell what they really wanted to achieve - to change that variable because “=” can be used as variable declaration and “+=” can’t. In my opinion this is somehow not beginner friendly?

I know you can use global keyword to access it, but the fact that any read-only operations e.g. print(global_var) does not need to use global is kind of confusing?

Any previous discussions? Would love to know, thanks…!

While the intention seems obvious the current rule is easy to follow once you know it, any kind of assignment in a function scope means that variable is local to that scope and you need to specify global if you want global.

In your example what scope would my_var have in func:

my_var = 0

def func():
    my_var += 1
    my_var = 2

func()

In the current rules it’s really easy it’s local because an assignment occurred inside func to my_var. But in your version did the += force it to be global or does that standard assignment of = force it be local? So would we now need to define a prescience of assignments and how they affect scope?

4 Likes

The rule is straightforward: ‘x += 1‘ uses the same scoping rule as ‘x = x + 1’.

It’s not going to change. Tutorial authors ought to make this clear.

Update: x += y is literally the same as x = x.__iadd__(y).

9 Likes