为什么sys.getsizeof()不在Python中的file.read([size])中返回[size]

sam*_*fer 0 python string file-io

我有一个大型的二进制文件,我想读入并使用struct.unpack()解压缩该文件包含多个行,每行长2957个字节.我使用以下代码读入文件:

with open("bin_file", "rb") as f:
    line = f.read(2957)
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么,尺寸返回:

import sys
sys.getsizeof(line)
Run Code Online (Sandbox Code Playgroud)

不等于2957(在我的情况下是2978)?

Mar*_*ers 7

你误解是什么sys.getsizeof() .它返回Python用于字符串对象的内存量,而不是行的长度.

Python字符串对象跟踪的引用计数,对象类型和其他元数据连同实际的字符,所以2978个字节是一样的东西作为字符串长度.

查看stringobject.h类型定义:

typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1];

    /* Invariants:
     *     ob_sval contains space for 'ob_size+1' elements.
     *     ob_sval[ob_size] == 0.
     *     ob_shash is the hash of the string or -1 if not computed yet.
     *     ob_sstate != 0 iff the string object is in stringobject.c's
     *       'interned' dictionary; in this case the two references
     *       from 'interned' to this object are *not counted* in ob_refcnt.
     */
} PyStringObject;
Run Code Online (Sandbox Code Playgroud)

其中PyObject_VAR_HEAD被定义在object.h,其中标准ob_refcnt,ob_type并且ob_size都被定义的字段.

所以,长度2957的字符串需要2958个字节(字符串长度+空),你看到剩余的20个字节来保存引用计数,类型指针,对象大小"(这里字符串长度),缓存字符串散列和实习国旗.

其他对象类型将具有不同的内存占用,并且所使用的C类型的确切大小也因平台而异.