10

How do I annotate a bytes-like object or a Buffer?

There is no interface for the buffer protocol but I wish to accept all buffers in a function of mine.

I don't mind if it's only mypy-specific.

Bharel
  • 23,672
  • 5
  • 40
  • 80

2 Answers2

3

Currently (as of Python 3.6) the "Buffer Protocol" is a C API thing only - you can't even talk about it in regular Python code.

cf: Add typing.py class describing a PEP 3118 buffer object

I would use Any for now.

3

Starting with Python 3.12, collections.abc.Buffer can be used like so:

from collections.abc import Buffer

def foo(buffer: Buffer):
    pass 
Bharel
  • 23,672
  • 5
  • 40
  • 80
  • Wow, it took them 8 years to come up with a type for it (since 3.5). I like Python, but type hints are like 'the interpreter doesn't care, we don't care, neither should you'. – Abhijit Sarkar Jun 22 '23 at 18:50
  • @AbhijitSarkar actually nowadays type-hints are used just about everywhere. CPython core devs tend to develop them more and more. – Bharel Jun 23 '23 at 00:26