Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

memory

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?

like image 383
bpceee Avatar asked Sep 01 '25 10:09

bpceee


1 Answers

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.

like image 152
6502 Avatar answered Sep 03 '25 00:09

6502