name space comprehension in python with if and else

Question:

code first:

# case01
def x():
    if False:
        #x2 = 22
        print x1
    else:
        print x2

if __name__ == '__main__':
    if False:
        x1 = 1
    else:
        x2 = 2
    x()

case01‘s output:

2

No problem! but when i uncomment #x2 = 22 in if False: block and rerun, it will got error:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-e36cb32b2c83> in <module>()
     11     else:
     12         x2 = 2
---> 13     x()

<ipython-input-4-e36cb32b2c83> in x()
      4         print x1
      5     else:
----> 6         print x2
      7 
      8 if __name__ == '__main__':

UnboundLocalError: local variable 'x2' referenced before assignment

As i see, if False: block will not excute, But why x2 = 22 take some effect to the script i worte?

My python version: 2.7.13

Asked By: CodeUnsolved

||

Answers:

Before start your script Python interpreter precompile it in a bytecode and when it sees “x2=22” in the function it puts x2 in __locals__ for that function and consider every ref to x2 as to local x2 not the global one. But when you start your function you don’t assign any value to the local x2 but Python still looking only for the local one, so you get the error.

I hope I explained in understandable manner, sorry for my unperfect English )))

Answered By: vZ10

x2 is not defined in the function x’s scope. Try moving “x2 = 22” out of the if statement, and it will work fine. Just for the record, doing “if False” is entirely useless, and is making the computer do an extra calculation. In this small of code it makes no difference but in bigger code there will be a noticeable difference in efficiency.

Answered By: Brendan Jordahl
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.