How does the "global" behave under the if statement?

In my program, I wanted the global variable to be only in some circumstances. Let's say it looks like this:

a = 0 def aa(p): if p: global a a = 1 print("inside the function " + str(a)) print(a) aa(False) print("outside the function " + str(a)) 

I expected the result would be:

 0 inside the function 1 outside the function 0 

However, it turned out:

 0 inside the function 1 outside the function 1 

So, I thought: β€œWell, maybe the Python compiler makes the global variable whenever it sees the keywordβ€œ global ”no matter where it is.” Is this how Python works with global vars? I do not understand?

+5
source share
1 answer

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!

+5
source

All Articles