Python gotcha - "is" operator on integers

in #python6 years ago (edited)

Screen Shot 2018-04-17 at 11.50.36 PM.png

I have been into this "quirk" again, today. You have probably no idea if you didn't encounter it yourself before.

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-) ref.


Have a look at Python3 docs and see the stackoverflow discussions to learn more.

And, please be safe with the small integers.

Sort:  

That can really cause some confusion. :)
Using is and testing with small integers, only to later find out it fails with larger values.

You should only use is with None. For there is and can only ever be one object of type NoneType. If a routine may return None, we know it isthe same constant None object used everywhere in Python.

That is if a==None and b==None then a is b. However, no such identity should be assumed for values other than None.

Followed and voted for Witness: thanks @emrebeyler for all cool things you do!
Have a happy day! ;)

very good idea.I also read your post.

I voted for you brother but never forget me when you will be a whale.

This post has received a 24.81 % upvote from @boomerang.

i vote you as a witnesses. plz upvote my comment

Coin Marketplace

STEEM 0.28
TRX 0.13
JST 0.033
BTC 62121.36
ETH 3004.20
USDT 1.00
SBD 3.71