7

Let's say I have a function:

def get_tuple():
    return (1,)

In IDLE if I call:

get_tuple() is get_tuple()

It will print True

If I call:

(1,) is (1,)

It will print False

Do you know why? I cannot find an explanation in the Python documentation.

Boann
  • 48,794
  • 16
  • 117
  • 146
Vadim Sentiaev
  • 741
  • 4
  • 18

3 Answers3

17

The CPython implementation of Python stores constant values (such as numbers, strings, tuples or frozensets) used in a function as an optimization. You can observe them via func.__code__.co_consts:

>>> def get_tuple():
...     return (1,)
...
>>> get_tuple.__code__.co_consts
(None, 1, (1,))

As you can see, for this function the constants None (which is the default return value), 1 and (1,) get stored. Since the function returns one of them, you get the exact same object with every call.

Because this is a CPython implementation detail, it's not guaranteed by the Python language. That's probably why you couldn't find it in the documentation :)

Neil G
  • 32,138
  • 39
  • 156
  • 257
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
6

Python optimizes the return value.
Because it is easy for the interpreter to see that the returned tuple will be the same each time, and it is an immutable object, it returns the same object (the exact same one. same memory address).
Here, when you do a is b you actually ask id(a) == id(b).

Yuval Ben-Arie
  • 1,280
  • 9
  • 14
0

Maybe it is because of addresses in the memory. Just try to print them via print memory address of Python variable

Kryštof Řeháček
  • 1,965
  • 1
  • 16
  • 28
  • 3
    @Kristofee yes for each call it returns same, but I cannot understand why, because i expect each function call will return new object. – Vadim Sentiaev Jul 22 '17 at 22:40