Monday, February 1, 2010

The whole truth...

The answer to an as yet unformulated Python trivia question:


>>> hex(id(True))
'0x1001163b0'
>>> hex(id(False))
'0x100116390'
>>> True = False
>>> hex(id(True))
'0x100116390'
>>> True == False
True
>>> b = True == False
>>> hex(id(b))
'0x1001163b0'
>>> b == False
False


If you're confused about the later part, I think what's happending is that when I do:
True == False
I have redefined the label 'True', but there are still circumstances where Python goes back to its original definition. In particular, with
b = True == False
the first thing is that Python looks up its 'True', (at 0x1001163b0) and evaluates whether it is True. It is, so the evaluation is short-circuited and Python's True is assigned to b. On the other hand, this doesn't work like I expect:


>>> False = (True == False)
>>> hex(id(False))
'0x100116390'

[ UPDATE: I think I've stepped into logical quicksand here. I assigned my label 'True' to Python's value for False. The comparison b = True == False evaluates to True, but that's Python's True, and assigns it to b. At the end, I just messed up somehow. The correct test is:

>>> hex(id(True))
'0x1001163b0'
>>> hex(id(False))
'0x100116390'
>>> False = (True == False)
>>> hex(id(False))
'0x100116390'
>>> True = False
>>> False = (True == False)
>>> hex(id(False))
'0x1001163b0'

No comments: