Two aces up Python's sleeve

Mild Shock janburse at fastmail.fm
Thu Nov 7 09:04:53 EST 2024


This only works for small integers. I guess
this is because tagged pointers are used
nowadays ? For large integers, also known

as bigint, it doesn't work:

Python 3.13.0a1 (tags/v3.13.0a1:ad056f0, Oct 13 2023, 09:51:17)

 >>> x, y = 5, 4+1
 >>> id(x) == id(y)
True

 >>> x, y = 10**200, 10**199*10
 >>> x == y
True
 >>> id(x) == id(y)
False

In tagged pointers a small integer is
directly inlined into the pointer. The
pointer has usually some higher bits,

that identify the type and when masking
to see the lower bits, one gets the
integer value.

But I don't know for sure whats going on,
would need to find a CPython documentation.

P.S.: I also tested PyPy it doesn't show
the same behaviour, because it computes
an exaberated id():

Python 3.10.14 (39dc8d3c85a7, Aug 27 2024, 14:33:33)
[PyPy 7.3.17 with MSC v.1929 64 bit (AMD64)]
 >>>> x, y = 5, 4+1
 >>>> id(x) == id(y)
True

 >>>> x, y = 10**200, 10**199*10
 >>>> id(x) == id(y)
True
 >>>> id(x)
1600000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000
000000000000000001

Quite funny!

Annada Behera schrieb:
>> Then please explain why I have to write:
>>
>>      i += 1
>>
>> Instead of the shorter:
>>
>>      i ++
>>
>> My short-term memory is really stressed.
> 
> I heard this behavior is because python's integers are immutable.
> For example:
> 
>      >>> x,y = 5,5
>      >>> id(x) == id(y)
>      True
> 
> 5 is a object that x and y points to. ++x or x++ will redefine 5 to
> 6, which the interpreter forbids to keep it's state mathematically
> consistent. Also, by not supporting x++ and ++x, it avoids the pre-
> and post-increment (substitute-increment v. increment-substitute) bugs
> that plagues C and it's children.
> 
> 



More information about the Python-list mailing list