0

I have looked around the forums and I can't seem to find an answer (and there might not be one actually) as to whether or not you can get the name of a variable or the value by using its memory location in Python. In other words, when I declare a = 10 and assign the value 10 to the variable 'a', and then I use the id() function on 'a' I get the location in memory where the value for 'a' is stored. Is there a way to, say, print the variable name ('a') or the value ('10') by referencing the value that id() returns (either the decimal value or converting the decimal value to hex with the hex() function)? I tried a few things like print(id(variable-name)) and just print(decimal-value-from-id) and no luck. Any help would be greatly appreciated and thank you in advance!

Cheers!

5
  • 4
    Why do you want to do that? Commented Nov 13, 2017 at 16:28
  • 2
    No. In fact, id(obj) being the location in memory of obj is a CPython implementation detail, and shouldn't be relied upon Commented Nov 13, 2017 at 16:31
  • You could probably do this in a C extension, but not pure python Commented Nov 13, 2017 at 16:33
  • Well you could store a dictionary of id values to variables, and intern your strings to ensure this is applied consistently, but what is your ultimate aim here? Commented Nov 13, 2017 at 16:36
  • Even though this is possible in CPython, it is highly inadvisable for you to rely on this. Also, it is important to note that the value returned by id isn't linked to the variable, but the object. Commented Nov 13, 2017 at 17:04

1 Answer 1

0

This is possible with ctypes:

import ctypes
a = 10
ctypes.cast(id(a), ctypes.py_object).value
#10

This will, of course, work if the object is still there.

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

3 Comments

I am very tempted to downvote this... You can guarantee that it only exists if you are holding a reference to that variable, in which case you could actually store it somewhere indexable with the ID.
Your concerns are in place and I wouldn't suggest this in production. Still, it is what OP wanted to do.
Zipa, thank you for your reply and this is what I was looking for. The reason I posted was that I was having a conversation about mutable vs. immutable and used the id() function to show that mutable objects like lists can be changed in place (where id() returns the same memory value/location) and an integer or string variable name returns a new id() value when changed (so can't be changed in place). Was asked how I could take the memory location value generated by id() to get the name or value of the variable stored at that location - kinda reverse engineer it so to speak. Thank you!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.