Seemingly odd 'is' comparison.
Duncan Booth
duncan.booth at invalid.invalid
Mon Feb 18 07:31:05 EST 2008
Tobiah <toby at tobiah.org> wrote:
> Subject: Seemingly odd 'is' comparison.
Please put your question into the body of the message, not just the
headers.
>>>> print float(3.0) is float(3.0)
> True
>>>> print float(3.0 * 1.0) is float(3.0)
> False
>>>>
>
>
> Thanks,
>
> Tobiah
>
Your values are already all floats so float() just returns its arguments.
In other words you can omit it:
>>> 3.0 is 3.0
True
>>> 3.0 * 1.0 is 3.0
False
3.0 used twice in the same compilation unit is the same constant value used
twice. 3.0 * 1.0 creates a new float value.
Compare with:
>>> n = 3.0
>>> n is 3.0
False
Here two separate compilations result in two separate values.
In general any immutable results of calculations which are the same may or
may not share the same object and this can vary according to the version of
Python or the phase of the moon. Only use 'is' when you actually care about
object identity, don't use it for a shorthand for '=='.
More information about the Python-list
mailing list