Accessing Object Memory Address
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 Question
00:34 Accepted answer (Score 256)
01:27 Answer 2 (Score 85)
01:43 Answer 3 (Score 64)
01:55 Answer 4 (Score 33)
05:49 Thank you
--
Full question
https://stackoverflow.com/questions/1213...
Accepted answer links:
[Python manual]: https://docs.python.org/2/library/functi...
Answer 4 links:
[id]: https://docs.python.org/3/library/functi...
[PyObject]: https://docs.python.org/3/c-api/object.h...
[C API]: https://docs.python.org/3/c-api/index.ht...
[pythonapi]: https://docs.python.org/3/library/ctypes...
[ctypes.addressof]: https://docs.python.org/3/library/ctypes...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #object #memoryaddress #repr
#avk47
ACCEPTED ANSWER
Score 266
The Python manual has this to say about id():
Return the "identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (CPython implementation detail: This is the address of the object in memory.)
So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.
Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.
ANSWER 2
Score 86
You could reimplement the default repr this way:
def __repr__(self):
return '<%s.%s object at %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self))
)
ANSWER 3
Score 65
Just use
id(object)
ANSWER 4
Score 14
Just in response to Torsten, I wasn't able to call addressof() on a regular python object. Furthermore, id(a) != addressof(a). This is in CPython, don't know about anything else.
>>> from ctypes import c_int, addressof
>>> a = 69
>>> addressof(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: invalid type
>>> b = c_int(69)
>>> addressof(b)
4300673472
>>> id(b)
4300673392