• Posted by Konstantin 21.10.2019 No Comments

    Can't help sharing this lovely example, illustrating the way Python interns small integers, the lower level use of the id function as well as the power of the ctypes module.

    import ctypes
    def deref(addr, type_):
        return ctypes.cast(addr, ctypes.POINTER(type_))
    
    deref(id(29), ctypes.c_int)[4] = 100
    > 29
    100
    
    > 29*100
    10000
    
    > 25+4
    100

    Note that depending on the version of Python the value of the integer may be stored at either offset [4] or [6].

    Tags: , , , ,