[Tutor] is v == for small ints

2015-12-14 Thread Alan Gauld
Somebody posted a question about this today and I approved
it but it hasn't shown up. We have had about 6 or 7 such
problems in the last month. Mainly they have been thank-you
messages so I didn't make an issue of it but a couple
have been genuine questions, like this was.

So if you have posted recently and it hasn't got through,
my apologies, but I have no idea what is going wrong.

As to the content of this message, the gist was that he had
tried 'is' and == with both small and large ints. When using
small ints the results were the same for both operators but
for large ints they differed. He knew the conceptual difference
between 'is' and == but didn't understand why the results
were different for large/small ints.

The answer is of course that small ints are cached internally
as an optimisation so all references to 5, for example,
refer to the same object in memory and therefore both is
(object identity) and == (value equality) are true. Large
ints result in two separate objects each with the same
value so 'is' becomes False and == remains true.

This behaviour should never be relied on since the definition
of a "small int" is potentially implementation dependant and
could even change with Python version or platform. Always
use == to test integers.

Apologies again about the missing messages.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is v == for small ints

2015-12-14 Thread Steven D'Aprano
On Tue, Dec 15, 2015 at 01:54:30AM +, Alan Gauld wrote:

> This behaviour should never be relied on since the definition
> of a "small int" is potentially implementation dependant and
> could even change with Python version or platform. Always
> use == to test integers.

It isn't just *potentially* implementation dependent, it certainly is 
implementation dependant.

Different versions of Python have used different rules for which small 
ints are cached, and the rules for when they will be re-used or cached. 
For example, this is with Python 2.7:


py> a = 11
py> b = 11
py> a is b
False
py> a = 12; b = 12
py> a is b
True


You CANNOT rely on this behaviour, it WILL change from version to 
version.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor