How to memory dump an object?

Ned Batchelder ned at nedbatchelder.com
Fri May 20 21:59:55 EDT 2016


On Friday, May 20, 2016 at 9:05:51 PM UTC-4, jf... at ms4.hinet.net wrote:
> Is there any tools which can do the memory dump of an object so I can view their content or implementation? For example,
> 
> >>> s1 = '\x80abc'
> >>> b1 = b'\x80abc'
> 
> What are exactly stored in memory for each of them? Is their content really the same? This kind of tool should be helpful "for me" to learn the inner detail of Python. 

I don't know of a tool that will do that, other than running CPython under
the gdb debugger, and examining memory that way.

In Python 2, those two objects are the same, because '...' is a byte string,
and b'...' is a byte string.

I should say, those objects' memory starts out exactly the same.  Objects have
reference counts which change as names come and go:

    >>> s1 = '\x80abc'
    >>> b1 = b'\x80abc'
    >>> b2 = b1

Now the first string has a reference count of 1, and b1 has a reference count
of 2. Those counts are in the objects' memory, so now their memory contents
are different.

--Ned.



More information about the Python-list mailing list