0

Considering this snippet:

globalvar = 1

def f():
 print globalvar

f()

why doesn't Python throw an exception like it would with the following two snippets?

(This one throws an exception)

globalvar = 1

def f():
 globalvar = 2

f()

And this one does too:

another_globalvar = 1

def f():
 print globalvar

f()

In other words, why doesn't Python enforce declaring globals for reading, like it does for "locals"?

  • Also see [here](http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules). – TigerhawkT3 Sep 27 '16 at 18:06
  • Keep in mind that if your question is really "why did the language designers think this was okay," the answer is "because they felt like it, and now this is how the language works." – TigerhawkT3 Sep 27 '16 at 18:06
  • See also http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – cdarke Sep 27 '16 at 18:07
  • 1
    The first doesn't throw an exception; it simply creates a local variable that shadows the global. The second doesn't define `globalvar` at *any* scope, so the exception is pretty obvious. – chepner Sep 27 '16 at 18:09
  • Consider functions declared outside a function, should you declare those as global too? If you did have to declare all globals then that would have to apply to functions as well, since they are "first class objects", in other words they are really no different to any other object in that respect. Personally I always use `global` even when I am reading, for documentary purposes (but not for functions) - it has no other effect and you can do the same. – cdarke Sep 27 '16 at 18:11

0 Answers0