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?

4
  • 1
    How about globals()["a"] = "world"? Would that fit your needs? There is also a locals() version of that as well. Commented Mar 10, 2022 at 20:35
  • pedantically, id() is not guaranteed to be the memory address of the object, and this is an implementation detail of CPython (though this is almost always the case) Commented Mar 10, 2022 at 20:49
  • 2
    Yes, there is. I recently did it with ints and you can similarly do it with strings. But you shouldn't. Why do you think you need to? Commented Mar 10, 2022 at 20:57
  • Here's an answer where you can do this in CPython, and also demonstrates why you shouldn't. Commented Mar 10, 2022 at 21:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.