I want to know how a Python variable (int, list, tuple) look like in memory. And this is where I am right now.
from ctypes import string_at
from sys import getsizeof
from binascii import hexlify
string_at(id(a), getsizeof(a))
I expect it will return the hex representation of a variable in the memory.
However, here is the output when I assign value 1,2,3 to variable 'a':
1 - '\xd6\x05\x00\x00\x00\x00\x00\x00\xc0\x92\x17\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00'
2 - '\x17\x02\x00\x00\x00\x00\x00\x00\xc0\x92\x17\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'
3 - '\xdc\x00\x00\x00\x00\x00\x00\x00\xc0\x92\x17\x00\x01\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'
4 - '\x06\x01\x00\x00\x00\x00\x00\x00\xc0\x92\x17\x00\x01\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'
Somewhere close to the middle, I can see \x01, \x02...etc. However, here are my other questions:
At the beginning, I can see two other bytes changing, what are those values?
Except for those \x00, I can see a few other bytes like ...\xc0\x92\x17\x00\x01...
how to interpret those values?
Is there any resource available for me to learn how python store variables in memory?
Download the Python C sources and study them. You'll see that "almost everything" is a PyObject*
-- a pointer to a PyObject
struct
. The \x01
&c you see are just random bytes within some of those pointers, nothing to do with the 1,2,3
tuple you're seeing, not directly at least!