Ashwin Nanjappa Ashwin Nanjappa - 4 years ago 95
Python Question

Python: Why is global needed only on assignment and not on reads?

If a function needs to modify a variable declared in global scope, it need to use the global declaration. However, if the function just needs to read a global variable it can do so without using a global declaration:

X = 10
def foo():
global X
X = 20 # Needs global declaration
def bar():
print( X ) # Does not need global

My question is about the design of Python: why is Python designed to allow the read of global variables without using the global declaration? That is, why only force assignment to have global, why not force global upon reads too? (That would make it even and elegant.)

Note: I can see that there is no ambiguity while reading, but while assigning it is not clear if one intends to create a new local variable or assign to the global one. But, I am hoping there is a better reason or intention to this uneven design choice by the BDFL.

Answer Source

Look at this code:

from module import function

def foo(x):
    return function(x)

The name function here is a global. It would get awfully tedious if I had to say global function to get this code to work.

Before you say that your X and my function are different (because one is a variable and the other is an imported function), remember that all names in Python are treated the same: when used, their value is looked up in the scope hierarchy. If you needed global X then you'd need global function. Ick.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download