Silly questions about True and False
Steven Bethard
steven.bethard at gmail.com
Mon Dec 20 14:04:11 EST 2004
drs wrote:
> I just upgraded my Python install, and for the first time have True and
> False rather than 1 and 0. I was playing around at the command line to test
> how they work (for instance, "if 9:" and "if True:" both lead to the
> conditional being executed, but True == 9 -> False, that this would be true
> was not obvious to me
Note that evaluating to True isn't the same as being equal to True.
Would you also expect that [] == None? Both evaluate to False in a
boolean context. Or an even better example, would you expect that
[1] == [2]? Both of these evaluate to True in a boolean context...
What you should expect is that:
py> bool([]) == bool(None) == False
True
py> bool([1]) == bool([2]) == True
True
> "True is True" is True, while "9 is True" is false
> even though 9 evaluates to True.)
Be careful here. 'is' tests object identity. So "9 is True" would only
evaluate to True if 9 is exactly the same object as True. 'is' won't
convert anything to a boolean; "x is y" basically translates to
"id(x) == id(y)".
> why doesn't False = 0 throw the same error?
Backwards compatibility. A lot of modules pre-False and True have code
that looks like:
True, False = 1, 0
or
True, False = (1 == 1), (1 == 0)
If assignment to True or False became a syntax error (which it probably
should be), it would break all such code.
> Also, why doesn't False = 0 make
>
>>>>1 == 2
> 0
>
> Instead of False?
You've only rebound the name False in your module's namespace. 1 == 2
executes the int code for equality, which presumably returns one of
Py_False or Py_True, not your binding for the name False in your module.
Steve
More information about the Python-list
mailing list