简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM