Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why python need global keyword while C/C++ no need?

If I want change a global variable, I could do it directly in C++:

#include <stdio.h>

int x = 1;

int main()
{
    x = 1 + x;
    printf("%d\n", x);
    return 0;
}

But got error using Python:

x = 1
def foo():
    x += 1

foo()

UnboundLocalError: local variable 'x' referenced before assignment

I have to add global x in function foo to make it.


Seems python make it more explicit, is "just to be explicit" the reason?

like image 461
roachsinai Avatar asked Mar 20 '26 20:03

roachsinai


2 Answers

The fundamental difference is that C and C++ have variable declarations. The location of the declaration determines whether a global is declared.

In Python, you only have assignments. An assignment to a yet-unassigned variable creates that variable. An assignment to an existing variable changes that variable. Hence, without global you couldn't create a local variable if a global variable with that name existed.

like image 87
MSalters Avatar answered Mar 22 '26 08:03

MSalters


without the global keyword, x doesn't exist in the function. When the parser sees

x += 1

it assumes that x is a local variable (because it's on the left hand side of the expression)

Now when += tries to change the value of the variable, since x doesn't exist as a local variable, it fails.

Note that it cannot be workarounded without the global keyword for immutable types, but for mutable types like list you could make without it.

This fails the same way as with integer, because the parser doesn't care about types:

x = []
def foo():
    x += [12]

but this works, as x isn't seen as a local by the parser.

x = []
def foo():
    x.extend([12])

At any rate, avoiding global variables avoids a lot of head-scratching. You can use other patterns most of the time (like singleton objects).

class MyTool:
   def __init__(self):
      self.x = 12
   def add_one_to_x(self):
      self.x += 1

m = MyTool()
m.add_one_to_x()

x is an instance variable, shared between all methods of your singleton object. See? no need for globals now (well, except for m but 1) there's only one global variable in the project and 2) it can also be defined in a main function)

like image 20
Jean-François Fabre Avatar answered Mar 22 '26 10:03

Jean-François Fabre