检查对象是否支持缓冲区协议python

2024-10-01 22:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在寻找Python C-API PyObject_CheckBuffer的Python等价物。在

例如,我想检查一个对象是否支持缓冲区协议,但是来自Python。在


Tags: 对象api协议缓冲区pyobjectcheckbuffer
2条回答

在处理性能关键代码的简短数据片段时,我不得不尝试不同的方法。根据您的应用程序,其中一个可能比其他更好。在

def ensure_bytes__try(data):
    try:
        # memoryview used only for testing type; 'with' releases the view instantly
        with memoryview(data):
            return data
    except TypeError:
        return data.encode()

def ensure_bytes__isinstance(data):
    # Explicitly test for some bytes-like types
    # - misses array.array, numpy.array and all other types not listed here
    return data if isinstance(data, (bytes, bytearray, memoryview)) else data.encode()

def ensure_bytes__hasattr(data):
    # Works as long as your bytes-like doesn't have 'encode'
    return data.encode() if hasattr(data, "encode") else data

def ensure_bytes__args(data=None, data_bytes=None):
    # Avoid autodetection by using explicit arguments
    return data_bytes if data is None else data.encode()

以下基准测试显示了Python 3.7.4上的每个实现所使用的时间:

^{pr2}$

短条意味着更快。每个条的浅色部分表示以ref_bytes(b"foo")(84 ns)和ref_str("foo")(100 ns)为基准的参考时间:

def ref_bytes(data): return data
def ref_str(data): return data.encode()

我认为你应该使用标准的方法,试试看它是否有效:

# New-style buffer API, for Python 2.7 and 3.x.
# PyObject_CheckBuffer uses the new-style API.
# 2.6 also has the new-style API, but no memoryview,
# so you can't use it or check compatibility from Python code.
try:
    memoryview(thing)
except TypeError:
    # Doesn't support it!

# Old-style API. Doesn't exist in 3.x.
# Not quite equivalent to PyObject_CheckBuffer.
try:
    buffer(thing)
except TypeError:
    # Doesn't support it!

相关问题 更多 >

    热门问题