variable declaration

Brian van den Broek bvande at po-box.mcgill.ca
Mon Feb 7 20:36:15 EST 2005


Steve Holden said unto the world upon 2005-02-07 17:51:
> Alexander Zatvornitskiy wrote:
> 
>> Привет Alex!
>>
>> 05 февраля 2005 в 17:00, Alex Martelli в своем письме к All писал:

<SNIP>

>>  AM> to all intents and purposes working "as if"
>>  AM> it was a declaration.  If I had to vote about the one worst formal
>>  AM> defect of Python, it would surely be 'global'.
>> Second worsest - 'def'? :)
>>
> The reason global is a wart can clearly be seen in the following example:
> 
>  >>> x = 3
>  >>> def f(tf, v):
>  ...   if tf:
>  ...     global x
>  ...   x = v
>  ...
>  >>> f(0, 5)
>  >>> x
> 5
>  >>>
> 
> This makes it apparent that the global statement is *not* executable, 
> the only one in the language that is not.

<SNIP>

> regards
>  Steve

Hi,

Steve's example makes my brain hurt. :-)

I'd appreciate it if someone could tell me if I am understanding the 
example correctly. (My grasp of the terminology and issues at play is 
a bit shaky.)

Let me simplify Steve's example to:

.def hurts_my_brain(v):
.    if False:     # unlike Steve's eg, ensuring that the
.        global x  # nested block is never hit at runtime
.    x = v

(I checked, and it works the same as the original eg, modulo change of 
function name.)

Is the right way to understand it in this vicinity:

At compile time (by which I mean when the Python bytecode is built) 
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'. At runtime, 
the `global x' is never reached, but it has already, at compile time, 
had its effect on the nature of the function object hurts_my_brain. 
Further, if the function had instead said 'if True:' the global 
statement would have been reached at runtime, but would have been 
without effect due to this, having already been `used up' in the 
creation of the bytecode.


Can it then be further (truly :-) ) said that

if False:
     # thousands of lines of code here

would effect the structure of the function object's bytecode, but not 
its behaviour when run? Or, at most, would cause a performance effect 
due to the bytecode being bloated by thousands of line's worth of code 
that would never get executed?

Thanks for any confirmation of my understanding / rectification of 
same. Best,

Brian vdB



More information about the Python-list mailing list