variable declaration

Terry Reedy tjreedy at udel.edu
Mon Feb 7 22:16:52 EST 2005


"Brian van den Broek" <bvande at po-box.mcgill.ca> wrote in message 
news:4208178F.40804 at po-box.mcgill.ca...
> Is the right way to understand it in this vicinity:

In the vicinity, but not quite exact

>At compile time (by which I mean when the Python bytecode is built)

Compile time is when the def statement is executed

>the global statement is hit and has the effect of `bumping up' the 
>function local name `x' to the module namespace, making the function local 
>name `x' synonymous with the module global name `x'.

Global make 'x' global.  Period.  There is no local 'x'.

> At runtime, the `global x' is never reached,

In CPython, at least, it is not even there to be reached (see below).
It is strictly a compile time declaration.  At runtime, it is equivalent to 
'pass'.

> but it has already, at compile time, had its effect on the nature of the 
> function object

Right.  With 2.2:

def f():
  if False: global x
  x = 1

import dis
dis.dis(f)
      0 SET_LINENO               1

      3 SET_LINENO               2
      6 LOAD_GLOBAL              0 (False)
      9 JUMP_IF_FALSE            7 (to 19)
     12 POP_TOP

     13 SET_LINENO               2
     16 JUMP_FORWARD             1 (to 20)
>>   19 POP_TOP

>>   20 SET_LINENO               3
     23 LOAD_CONST               1 (1)
     26 STORE_GLOBAL             1 (x)
     29 LOAD_CONST               0 (None)
     32 RETURN_VALUE

Two points: there is no byte code for the global declaration; x is directly 
stored as global.

Terry J. Reedy






More information about the Python-list mailing list