'Modify data in memory with python
suppose I have a variable with a numeric value of 20. we used the id() function to get its memory address. How can the numeric value of 20 be changed to, for example , 40 using the memory address?! as a result, I have 40 outputs by calling x
x = 20
# the memory address for x variable
address = id(x)
# how to assign 40 to the memory address(address)
# my result should be like the following line
print(x)
# 40
Solution 1:[1]
One ordinarily do not to that in Python: it is not the language designed for that: int
in Python is a high level, imutable object, and once you need an int with a different value, you will have another object, in another memory location.
But, there are data structures that store numbers as understood by the CPU in memory. One of them is the one used by bytearray
, which essentially works as a C char pointer (string).
Changing a value in a bytearray will change its value inplace, in memory - but the value returned by the "id" of a bytearray is not the data address, it is the address of the object header. Again: when coding in Python, messing with "absolute" (in process) memory addresses is not a priority.
In [30]: x = bytearray(b"Hello World")
In [31]: x.decode()
Out[31]: 'Hello World'
In [32]: x[0] -= 7
In [33]: x.decode()
Out[33]: 'Aello World'
It is possible, by making use of ctypes
, which allows for low level memory manipulation, and actually using the numbers returned by id
as memory pointers: yo u still would have to reach the exact offset of the number value to change an int
in place, and, as that is not an expected behavior, it would probably (and often does) lead to interpreter segfault - as the int
immutability is a premise for the code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |