Skip to content

Instantly share code, notes, and snippets.

Last active October 26, 2022 11:50
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Display the source blob
Display the rendered blob
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Copy link

Thanks for sharing. There is one inconsistency, which is my favorite)

In [1]: a = 1

In [2]: b = 1

In [3]: a is b
Out[3]: True

In [4]: a = 1000

In [5]: b = 1000

In [6]: a is b
Out[6]: False

Copy link

Oh yes, that one! It gets better though:

>>> def foo():
...     a = 1000
...     b = 1000
...     return a is b
>>> foo()

The reason is that the constants used here are stored in the function object, where they're deduplicated:

>>> foo.__code__.co_consts
(None, 1000)

So inside the function both the literals are looked up as the same constant.

There is basically zero behaviour you can count on for when two numbers are going to be reference equal in Python.

Copy link

kxepal commented Dec 16, 2015

Similar things are not always similar.

Python 3.4.3 (default, Nov 12 2015, 20:43:56) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a, b = b'foo', b'foo'
>>> a is b
>>> a, b = 'foo', 'foo'
>>> a is b
>>> a = 'foo'
>>> b = 'foo'
>>> a is b
>>> a = b'foo'
>>> b = b'foo'
>>> a is b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment