Home Getting Python variable name or value from memory location?
Reply: 1

Getting Python variable name or value from memory location?

Travis P. Bonfigli
Travis P. Bonfigli Published in 2017-11-13 16:24:54Z

This question already has an answer here:

  • Can I get a python object from its memory address? 2 answers

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!


zipa Reply to 2017-11-13 16:38:47Z

This is possible with ctypes:

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

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.351427 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO