variable declaration

Antoon Pardon apardon at forel.vub.ac.be
Thu Feb 10 04:23:13 EST 2005


Op 2005-02-08, Fredrik Lundh schreef <fredrik at pythonware.com>:
> Peter Otten wrote:
>
>>> executed. the compiler handles "global" and "from __future__", everything
>>> else is done at runtime.
>>
>> and __debug__, too, it seems:
>
> you left out the "python -O" line.
>
>>>>> __debug__
>> False
>>>>> def f():
>> ...     if __debug__:
>> ...             global x
>> ...     x = 42
>> ...
>>>>> f()
>>>>> x
>> Traceback (most recent call last):
>>  File "<stdin>", line 1, in ?
>> NameError: name 'x' is not defined
>
> yup, but unlike the two others, that's a CPython -O implementation issue.
> (I'd say bug, in this case).
>
> neither standard CPython (without -O) nor Jython behave this way.
>

If people here are so against declarations, how do they feel about
statements that don't seem like declarations but have a declarative
effect anyway?

Because that is what assignment statements in python essentially are.
If assignments wouldn't have a declarative effect then code like
the following should work:

x = 42

def f():
  if False:
    x = 20
  return x

f()


If the x = 20 would be a pure executing statement, then how come
its presence has an effect on the return statement even when it
isn't executed. And we can play the same trick here. calling python -O
and feeding it this program but with the False replaced by __debug__
will make this "work".

So having come to the conclusion that some statements have a declarative
effect, I would prefer to have the declaration and the assignment be
seperated in two different statements. That would make the declaration
explicit instead of being implicit now and explicit is better than
implicit.

Of course the other solution, simply removing the declarative effect from
assignments, could work too and might even be preferable but I fear
it would produce strange behaviour.

-- 
Antoon Pardon



More information about the Python-list mailing list