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!

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • 4
    Why do you want to do that? – wwii Nov 13 '17 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 – Patrick Haugh Nov 13 '17 at 16:31
  • You could probably do this in a C extension, but not pure python – Patrick Haugh Nov 13 '17 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? – Chris_Rands Nov 13 '17 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. – juanpa.arrivillaga Nov 13 '17 at 17:04

1 Answers1

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.

zipa
  • 27,316
  • 6
  • 40
  • 58
  • 1
    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. – Antti Haapala -- Слава Україні Nov 13 '17 at 16:43
  • Your concerns are in place and I wouldn't suggest this in production. Still, it is what OP wanted to do. – zipa Nov 13 '17 at 16:47
  • 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!! – Travis P. Bonfigli Nov 13 '17 at 18:08