John Gann
John Gann

Reputation: 605

When Python gives you the memory location of an object, what's that for?

When python gives me the location of an object in memory, what is that for, other than distinguishing between instances in the interactive prompt?

Example:

>>>inspect.walktree
<function walktree at 0x2a97410>

Upvotes: 4

Views: 3842

Answers (3)

Niklas B.
Niklas B.

Reputation: 95298

This is the default string representation that is returned if you call repr(obj) on an object which doesn't define the magic __repr__ method (or didn't override the default implementation inherited from object, in the case of new-style objects).

That default string has the purpose of giving the programmer useful information about the type and identity of the underlying object.

Additional information

Internally, the id function is called to get the number included in the string:

>>> o = object()
>>> o
<object object at 0x7fafd75d10a0>
>>> id(o)
140393209204896
>>> "%x" % id(o)
'7fafd75d10a0'

Note that id does NOT represent a unique ID. It can happen that during the lifetime of a program several objects will have the same ID (although never at the the same time). It also does not have to correlate with the location of the object in memory (although it does in CPython).

You can easily override the representation string for your own classes, by the way:

class MyClass(object):
  def __repr__(self):
    return "meaningful representation (or is it?)"

Upvotes: 5

jcollado
jcollado

Reputation: 40374

This is an implementation detail and you shouldn't rely on it:

$ python
>>> import inspect
>>> inspect.walktree
<function walktree at 0x7f07899c9230>
>>> id(inspect.walktree)
139670350238256

$ jython
>>> import inspect
>>> inspect.walktree
<function walktree 1>
>>> id(inspect.walktree)
1

The number being displayed is just an identity that can be use for testing with the is operator to check if two object are the same one. As already said, Whether that number is a memory location or not, is an implementation detail.

Upvotes: 2

Oleh Prypin
Oleh Prypin

Reputation: 34116

This is just a default representation for objects that don't have the __repr__ magic method.

Indeed, the address has no other purpose than "distinguishing between instances".

Upvotes: 5

Related Questions