bpceee
bpceee

Reputation: 416

How to print out the memory contents of object in python?

As in C/C++, we can print the memory content of a variable as below:

double d = 234.5;
unsigned char *p = (unsigned char *)&d;
size_t i;
for (i=0; i < sizeof d; ++i)
    printf("%02x\n", p[i]);

Yes, I know we can use pickle.dump() to serialize a object, but it seems generated a lot redundant things.. How can we achieve this in python in a pure way?

Upvotes: 4

Views: 4317

Answers (2)

6502
6502

Reputation: 114461

The internal memory representation of a Python object cannot be reached from the Python code logical level and you'd need to write a C extension.

If you're designing your own serialization protocol then may be the struct module is what you're looking for. It allows converting from Python values to binary data and back in the format you specify. For example

import struct
print(list(struct.pack('d', 3.14)))

will display [31, 133, 235, 81, 184, 30, 9, 64] because those are the byte values for the double precision representation of 3.14.

NOTE: struct.pack returns a bytes object in Python 3.x but an str object in Python 2.x. To see the numeric code of the bytes in Python 2.x you need to use print map(ord, struct.pack(...)) instead.

Upvotes: 3

Johan R&#229;de
Johan R&#229;de

Reputation: 21368

You can not do this in pure python. But you could write a Python extension module in C that does exactly what you ask for. But it would probably will not be very useful. You can read more about extension modules here

I assume that by Python you mean C-Python, and not PyPy, Jython or IronPython.

Upvotes: 1

Related Questions