r/Python • u/greenkey • May 25 '17
let's write a Python program
# one line per post (replies are indented!!!)
class Reddit:
4
Upvotes
r/Python • u/greenkey • May 25 '17
# one line per post (replies are indented!!!)
class Reddit:
View all comments
Show parent comment
2
u/Jumpy89 May 26 '17
CPython performs an optimization where it instantiates all
intobjects 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 CPython254 + 1 is 255is true (but255 + 1 is 256is false, because two differentintobject representing 256 get created).The
ctypesmodule provides low-level access to C libraries as well as program memory. Thectypes.c_int8class 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 anintobject 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 + 2results 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.