Mutating immutable objects with ctypes


1 Like

I wouldn’t call manipulating memory via ctypes “within Python”, but I can certainly see the argument to the contrary.

1 Like

It’s using Python code and not calling on any external code other than the standard library!

That said, though, changing the value of an integer is NOT what we would call, uhh, normal behaviour. If you change the value of 0 to be 42 and the interpreter crashes in approximately three nanoseconds, you can’t exactly complain about a bug.

(Trust me, a LOT of things get confused if zero becomes truthy.)

1 Like

To me, this ‘gotcha’ comment is not only a distraction from the subject of the thread, but is wrong. @kknechtel said “within Python”. The SO answer uses the CPython implementation’s interface to foreign non-Python functions. So “within CPython with cytpes or similar non-Python function access allowed, int object values can be mutated”. Karl, please feel free to write sensibly, as you did, without adding a caveat to every comment.

Most every statement in the Python docs inplicitly assumes that one has not called an implementation-specific foreign function that contradicts the statement. The docs effectively describe Python behavior on a pure Python interpreter that does not have such possibilities. Github python/cpython Issues that report “by using ctypes I made CPython misbehave” get rejected and closed.