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.
Functions can return tuples as return values.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With