How Does Python's Global Keyword Work?
Solution 1:
Any assignment to a name in a function makes the name local to the function. It doesn't matter where in the function the assignment is, even if it's the last statement in the function: the name is local to the function. If you use a local name before it's been assigned to, you get the error you see.
It doesn't matter that the name is also available in the global scope. The compiler knows that the name is local, and will only look for it in the local scope.
An import statement is a form of assignment. Your "import json" statement in the function makes the name "json" local to the function. You are using the name before it's been imported locally, so you are using an unbound local.
The "global" statement means, even though this name is used in an assignment statement, it's not a local name, it's a global name. In your second function, the global statement makes the name "json" refer to the global "json", which is already defined when you try to access it, so your function works.
Solution 2:
python sees the import json
statement when it first parses the function code and it decides that json
is a local variable. (The same thing will happen if you assign to json
-- e.g. json = 'Hello World!'
). When the expression json.dumps
executes, python looks for json
in the local scope and doesn't find it (hence the exception).
In the second case, when you add global
, when the function is parsed, you're telling python to always look for json
in the global scope. In your case, it exists there since you already imported it so it's all good. It also tells python that any assignments (or imports) of json
should store the name (and associated value) on the global scope rather than in the local scope.
Solution 3:
In Python there are local(default) and global contexts. A new local context is separately initialized for each function, when function starts it is empty. Global context is, well, global, and is shared by (almost) every part of your module.
By using global directive you import a variable from global context, preventing symbol lookup in the local one (which is empty and would otherwise fail).
Post a Comment for "How Does Python's Global Keyword Work?"