When you call the object.__repr__()
method in python you get something like this back: <__main__.Test object at 0x2aba1c0cf890>
, is there any way to get a hold of the memory address if you overload __repr__()
, other then calling super(Class, obj).__repr__()
and regexing it out?
views:
1711answers:
6You can get something suitable for that purpose with:
id(self)
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. (Implementation note: this is the address of the object.)
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.
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))
)
With ctypes, you can achieve the same thing with
>>> import ctypes
>>> a = (1,2,3)
>>> ctypes.addressof(a)
3077760748L
Documentation:
addressof(C instance) -> integer
Return the address of the C instance internal buffer
Note that in CPython, currently id(a) == ctypes.addressof(a)
, but ctypes.addressof
should return the real address for each Python implementation, if
- ctypes is supported
- memory pointers are a valid notion.
Edit: added information about interpreter-independence of ctypes
While it's true that id(object)
gets the object's address in the default CPython implementation, this is generally useless... you can't do anything with the address from pure Python code.
The only time you would actually be able to use the address is from a C extension library... in which case it is trivial to get the object's address since Python objects are always passed around as C pointers.