0
>>> class mytest():
...     pass
... 
>>> x=mytest()
>>> id(x)
140696428216768
>>> x
<__main__.mytest object at 0x7ff670a001c0>
>>> int(0x7ff670a001c0)
140696428216768

We know that 0x7ff670a001c0 or 140696428216768 is the address of variable x. How can get the variable name from address ?

>>> import ctypes
>>> ctypes.cast(140696428216768, ctypes.py_object).value
py_object(<__main__.mytest object at 0x7ff670a001c0>)    
>>> ctypes.cast('0x7ff670a001c0', ctypes.py_object).value
Segmentation fault
showkey
  • 482
  • 42
  • 140
  • 295
  • Related: [Python inverse function of id(...) built-in function](https://stackoverflow.com/questions/24815771/python-inverse-function-of-id-built-in-function) – khelwood Oct 30 '21 at 08:52
  • 1
    The id is related to an object, not to the name(s) that might have been given to it. – Thierry Lathuille Oct 30 '21 at 08:59
  • 2
    The `id` you get is not the address of the variable `x`. It is the address of the *value* held by `x`. So you're not going to be able to retrieve the name of the variable from the id that way. Presumably you could iterate through all the variables and see which one (or more) indicates that id. – khelwood Oct 30 '21 at 08:59
  • Removing the quotes where you specify the id should remove your segmentation fault. But,, as mentioned this will return the value rather than the name of the object. – DarrylG Oct 30 '21 at 09:03
  • 1
    Recommended reading: https://nedbatchelder.com/text/names.html. It would be helpful to include the context of _why_ you think you want to do this. – jonrsharpe Oct 30 '21 at 09:04
  • You can compare it to the id of every variable in the `locals()` and `globals()` dictionaries, See my answer to the [question](https://stackoverflow.com/questions/69774715/is-there-any-way-to-convert-a-list-to-dict-with-variable-names-staying-the-sam). – martineau Oct 30 '21 at 10:09

0 Answers0