global and loop control variable

Steven D'Aprano steve at pearwood.info
Thu Jul 23 14:31:54 CEST 2015


On Thu, 23 Jul 2015 09:20 pm, Lorenzo Sutton wrote:

> On 23/07/2015 12:24, candide wrote:
>> Now, global declaration has another restriction, as PLR explains:
>>
[https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement]
>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>> Names listed in a global statement must not be defined as formal
>> parameters or in a for loop control target,
>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>
>> What I understand is that the following is a must-not-code:
>>
>> def f():
>>      global i
>>      for i in range(1,3):
>>          print(10*i)
[...]
>> So my question is: what is the restriction about global as loop control
>> variable the docs is referring to?

You are correct. The above example is exactly the restriction mentions. The
very next paragraph in the docs says:

"CPython implementation detail: The current implementation does not enforce
the two restrictions, but programs should not abuse this freedom, as future
implementations may enforce them or silently change the meaning of the
program."

In other words, the behaviour of global loop variables is not guaranteed,
and you should not use it even if the compiler/interpreter fails to raise a
syntax error.


> I think for situations like this one?
> 
> def f():
>      global temperature
>      for temperature in range(1,3):
>          print "In f temperature is:", temperature


There's no meaningful difference between the example Candide gave (for i in
range) and the example you give (for temperature in range). They both use a
global for the loop variable. Only the names differ.


-- 
Steven



More information about the Python-list mailing list