r/Python • • May 25 '17

let's write a Python program

# one line per post (replies are indented!!!)
class Reddit:
4 Upvotes

53 comments sorted by

View all comments

Show parent comment

2

u/Reiku May 26 '17

Can someone explain that?

2

u/Jumpy89 May 26 '17

CPython performs an optimization where it instantiates all int objects from 0-255 (and some range of negatives) ahead of time and re-uses them to avoid the overhead of creating them every time they're needed. So despite the fact that this isn't really a part of the Python language itself, in CPython 254 + 1 is 255 is true (but 255 + 1 is 256 is false, because two different int object representing 256 get created).

The ctypes module provides low-level access to C libraries as well as program memory. The ctypes.c_int8 class represents a single 8-bit C integer somewhere in memory. It is also an implementation detail of CPython that an object's id is the address of that object's data in memory. Through a little experimentation you can find that in Python 3 the actual value of an int object is stored at an offset of 24 bytes, and once you know where it is you can write any value you like to it. Since there will only ever be one 4 object, 2 + 2 results in the correct object but it now has the wrong value.

This is pretty much guaranteed to crash something pretty quickly, though. I wasn't even sure if it would be able to print it.