jAckOdE
jAckOdE

Reputation: 2510

What is the scope of global variable in this case?

I'm new to python, so this is probably a dumb question.

Take this sample code:

y, z = 1, 2
def all_global():
    global x
    x = y + z

print(x,y,z)

As I understand, the global statment will declare global var x, and the print statement should print out 3,2,1

But I got

NameError: global name 'x' is not defined

So what does the global statement actually do in this case?

Upvotes: 1

Views: 43

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125398

Yes, the function makes x a global, but x will only be bound if all_global() is actually called. Until then, there is no name x bound.

In other words, it is not enough to declare x a global in a function; all it does is alter what namespace x will be set in when the function runs, it will not pre-define the name. What would it be bound to in that case?

Calling the function sets x and the print() call works:

>>> y, z = 1, 2
>>> def all_global():
...     global x
...     x = y + z
... 
>>> print(x,y,z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> all_global()
>>> print(x,y,z)
3 1 2

Upvotes: 4

Related Questions