1

For example, I have a variable called a, and need to change it by its memory address:

a: str = "hello"
address: int = id(a)

change_by_address(address, a, 'newval') # is something like this possible?

Is there some way to do this, perhaps in the ctypes library?

ZeroIntensity
  • 47
  • 1
  • 5
  • How about `globals()["a"] = "world"`? Would that fit your needs? There is also a `locals()` version of that as well. – JonSG Mar 10 '22 at 20:35
  • pedantically, `id()` is not guaranteed to be the memory address of the object, and [this is an implementation detail of CPython](https://docs.python.org/3/library/functions.html#id) (though this is almost always the case) – ti7 Mar 10 '22 at 20:49
  • 2
    Yes, there is. I recently [did it with ints](https://stackoverflow.com/a/70882093/12671057) and you can similarly do it with strings. But you shouldn't. Why do you think you need to? – Kelly Bundy Mar 10 '22 at 20:57
  • Here's [an answer](https://stackoverflow.com/a/63970638/235698) where you can do this in CPython, and also demonstrates why you shouldn't. – Mark Tolonen Mar 10 '22 at 21:34

2 Answers2

1

Well you can read by address in python:

import ctypes


a = 10
memfield = (ctypes.c_int).from_address(id(a))
print(memfield) # c_int(15)

But as far as I know, you cannot change values by address.

MartinKondor
  • 412
  • 4
  • 14
0

Absolutely, positively not. That ID is an address of SOMETHING in memory, but in C terms these are all moderately complicated data structures.

Python is not C. You cannot think of things in the same way.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 1
    At least in CPython, you *can* do it, but corrupting what is in the OP's case an immutable `str` is definitely a bad idea. – Mark Tolonen Mar 10 '22 at 21:31