Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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>
like image 854
John Gann Avatar asked Oct 19 '25 14:10

John Gann


1 Answers

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?)"
like image 197
Niklas B. Avatar answered Oct 22 '25 03:10

Niklas B.