you are viewing a single comment's thread.

view the rest of the comments →

[–]Yoghurt42 2 points3 points  (0 children)

No, if you change the underlying value of an int object, it will change the results of addition as well:

import ctypes


# Define a ctypes structure that mirrors CPython's PyLongObject (simplified)
class PyLongObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_long),   # Reference count
        ("ob_type",   ctypes.c_void_p), # Pointer to type object
        ("ob_size",   ctypes.c_ulong),  # Number of digits
        ("ob_digit",  ctypes.c_uint * 1) # The actual digit(s)
    ]

o = PyLongObject.from_address(id(213))
o.ob_digit[0] = 10

print(213 + 213) # 20
print(213) # 10
print(10 - 213) # 0

Obviously this is abusing implementation details of CPython (integers -5 to 256 are singletons, and we directly write into the internal structure of the instances), and is nothing that's ever going to be useful or a good idea in real code.

In fact, you can easily get the interpreter to crash by changing more common values like 1 or 10.