Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these tuples returned from a function identical?

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.

like image 639
Vadim Sentiaev Avatar asked Jul 22 '17 22:07

Vadim Sentiaev


People also ask

Can functions return a tuple?

Functions can return tuples as return values.

Should a function always return the same type?

Rule 1 -- a function has a "type" -- inputs mapped to outputs. It must return a consistent type of result, or it isn't a function.

What is the advantage of tuple as returning function argument?

Tuples provide a third way of returning multiple function values, one that combines aspects of the structure-based and on-the-fly options already mentioned. With tuples, you define the values to be returned as part of the function declaration, a bit like the out-parameter variation.

Can tuple have same value?

Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index [0] , the second item has index [1] etc.


1 Answers

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 :)

like image 159
Eugene Yarmash Avatar answered Dec 18 '22 17:12

Eugene Yarmash