I have a question about variable size in python, I'm using the the Ctypes because i want a 1 byte number, but when I tried to check it's size in python (via sys.getsize
) it said it was 80 byte but when i checked with the ctypes (via ctypes.sizeof
) it said it was 1 byte only, can someone tell me what is the difference and why is there 2 different sizes? is it because python is using an object or wrapper? and when its sent to c it views the real size?
import sys
import ctypes
print("size in ctypes is : ",ctypes.sizeof(ctypes.c_byte(1)))
print("size in sys is : ",sys.getsizeof(ctypes.c_byte(1)))
results in
size in ctypes is : 1
size in sys is : 80
The ctypes module is used for creating and manipulating C data types in Python. That is why ctypes.sizeof(ctypes.c_byte(1)) returns 1.
while
If you want to know the details, you should take a look at
objects.h
(especially the comments at the top of the file). Yourctypes.c_byte(1)
is a Python object:As noted by @Daniel,
sys.getsizeof
gets the size of that Python object. That Python object is larger than the corresponding object in C. Note the following from theobject.h
comments:In other words, a macro
PyObject_HEAD
is attached to the start of every object. This increases the size of the Python object.ctypes.sizeof
, on the other hand, returns the actual size of theC
data type that is within the Python object (using C'ssizeof
operator).EDIT
In light of your goal that you mention in your comment to Daniel's post, it is possible to send one byte over a server in Python 3.x. Below is an example of how you would send a byte using Python's
socket
module to prove this point.Here is the server, which you will run in one Python interpreter:
Here is the client, which you will run in another python interpreter:
sys.getsizeof
returns the size of a python object, this has nothing to do with the size of a C data type. And it is nothing you have to concern about.