DEV Community

Discussion on: 3 Tricky Python Nuances

Collapse
 
nviard profile image
Nicolas Viard

1) you should use a linter like pylint to avoid mistakes like this
2) is can be confusing for small integers because they share references
1 is 1 = True
158896587456 is 158896587456 = False

Collapse
 
modaf profile image
Modaf

I tried 158896587456 is 158896587456 on Python 3.6.1 and it answers True :/
(Even with huge numbers it does answer True)

Collapse
 
nviard profile image
Nicolas Viard

Sorry, this is true when (at least) one of them is stored into a variable:

>>> a = 1
>>> b = 1
>>> print(a is b)
True
>>> a = 123456789
>>> b = 123456789
>>> print(a is b)
False
Thread Thread
 
modaf profile image
Modaf

Indeed ! But it's weird that 123456789 is 123456789 = True, isn't it ? As if Python answers True for a is b if "a is the same as b" before testing if they are the same. Is there a reason for that ?

(123456789+0) is 123456789 = False
but 123456789 is 123456789 = True

Anyway thanks for the example and the answer !

Thread Thread
 
veky profile image
Veky • Edited

Optimizer gets better and better. In 3.7, even 123456788+1 is 123456789 gives True. It's simply that Python realizes it can evaluate constant pure expressions before compiling to bytecode. And it folds constants, of course.

>>> compile('123456788+1 is 123456789', '', 'eval').co_consts

You'll notice there's only one 123456789 there, not two. And there are no 123456788 nor 1.

Collapse
 
thejessleigh profile image
jess unrein • Edited

1.) I mean. I almost always find “you should use a linter and then you can avoid learning” to be an unhelpful piece of advice. Also, a linter’s not going to tell you why a nested array is behaving unexpectedly.
2) And true. Python can definitely get a little weird around the edges when you get to arbitrarily large numbers. I hope you’re not hardcoding and checking for identity for integers like this in your code.

You clearly understand references very well! These short examples are, of course, aimed at introducing a concept and encouraging people to learn more. Thanks for providing some trivia!