Yes, you understand things correctly.
The global statement is not what was evaluated at runtime. This is indeed a directive for the parser, which essentially tells it to treat all of the identifiers listed ( a here) as a global scope. From the documents, the global instruction :
A global statement is an announcement that runs for the entire current block of code. This means that the listed identifiers should be interpreted as global.
He then goes on to indicate how global really a directive:
Programmers Note: global is a parser directive.
Using this conditionally does not matter: its presence has already been detected at the parsing stage and, as a result, the bytecode generated to capture the names has already been configured for viewing in the global area (with LOAD/STORE GLOBAL ).
That is why, if you dis.dis is a function containing the global operator, you will not see the corresponding byte code for global . Using a dumb function:
from dis import dis def foo(): "I'm silly" global a dis(foo) 2 0 LOAD_CONST 0 (None) 2 RETURN_VALUE
For global a nothing is generated, because the information it provides is already in use!
source share