Welcome, guest | Sign In | My Account | Store | Cart

This is just an experiment to test my mental understanding of Python. It should not be used in any code as is violates the design principle that floats are to be immutable. The code also abuses ctypes and an understanding of how floats are currently arranged in memory. set_float is not guaranteed to work properly on any system, and may fail to work in the future if the data's arrangement changes.

Python, 10 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import sys, struct, ctypes

def set_float(obj, value):
    assert isinstance(obj, float), 'Object must be a float!'
    assert isinstance(value, float), 'Value must be a float!'
    stop = sys.getsizeof(obj)
    start = stop - struct.calcsize('d')
    array = ctypes.cast(id(obj), ctypes.POINTER(ctypes.c_ubyte))
    for args in zip(range(start, stop), struct.pack('d', value)):
        array.__setitem__(*args)

The following is a simple demonstration of how the set_float function could be used. Its implementation was meant as a test of understanding how both ctypes and Python work.

>>> a = 1.2
>>> set_float(a, 3.4)
>>> a
3.4