Python - Why do nonlocal and global variables need to be declared?

Why is the following piece of code in a plain Python 3.x module considered invalid syntax? I'm interested in the design considerations that guided the decision of requiring explicit declaring of global and nonlocal variables before assignment.

def foo():
    global a = 1

Upvotes: 0

Views: 291

Answers (2)

Yossarian42
Yossarian42

Reputation: 2050

global keyword indicates that the variable should be looked up in the global namespace as in globals(). It's nothing like const declaration in c++. So before you refer to the global a = 1, the variable a should've been created.

def foo():
    global a

This works fine without SyntaxError. But since a is not defined before function foo, the interpreter will return a NameError when you call foo().

In conclusion, keyword global is used to modify a variable defined in global scope inside a local scope like a function.

Upvotes: 0

nonameable
nonameable

Reputation: 446

From https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value:

This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope

This suggests the previous declaration of global a before altering its value is a safety measure for the programmer. Another reason may be that Python is is a dynamically-typed language, so if you think about it, that particular line looks nothing like regular Python code.

I encourage you to read https://docs.python.org/3/reference/simple_stmts.html#the-global-statement and experiment with the language. Finally, you could ask a core developer of the language in one of its mailing lists here: https://www.python.org/community/lists/. If you find anything interesting, please share it with the community.

Upvotes: 2

Related Questions