views:

1711

answers:

6

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?

+3  A: 

Just use

id(object)
Ben Hoffstein
+1  A: 

You can get something suitable for that purpose with:

id(self)
Thomas Wouters
+9  A: 

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.

Nick Johnson
+2  A: 

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))
    )
Armin Ronacher
Your reply is missing a closing parenthesis for hex(, and also seems to be incorrect for the question asked.
ΤΖΩΤΖΙΟΥ
Don't think so. The question was about overloading repr. So it makes sense to know how repr works internally.
Armin Ronacher
+4  A: 

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

Torsten Marek
A: 

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.

Dan