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

前端 未结 4 1134
一向
一向 2020-12-09 15:00

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 ca

4条回答
  •  醉话见心
    2020-12-09 15:32

    Because explicit is better than implicit.

    There's no ambiguity when you read a variable. You always get the first one found when searching scopes up from local until global.

    When you assign, there's only two scopes the interpreter may unequivocally assume you are assigning to: local and global. Since assigning to local is the most common case and assigning to global is actually discouraged, it's the default. To assign to global you have to do it explicitly, telling the interpreter that wherever you use that variable in this scope, it should go straight to global scope and you know what you're doing. On Python 3 you can also assign to the nearest enclosing scope with 'nonlocal'.

    Remember that when you assign to a name in Python, this new assignment has nothing to do with that name previously existing assigned to something else. Imagine if there was no default to local and Python searched up all scopes trying to find a variable with that name and assigning to it as it does when reading. Your functions' behavior could change based not only on your parameters, but on the enclosing scope. Life would be miserable.

提交回复
热议问题