Skip to content

Commit 42a9818

Browse files
committed
Add a challenge for buffer type
1 parent 6efc89c commit 42a9818

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
TODO:
3+
4+
Annotate the function `read_buffer`, which accepts anything that is a buffer.
5+
6+
See https://docs.python.org/3.12/reference/datamodel.html#object.__buffer__
7+
"""
8+
9+
10+
def read_buffer(b):
11+
...
12+
13+
14+
## End of your code ##
15+
16+
from array import array
17+
18+
19+
class MyBuffer:
20+
def __init__(self, data: bytes):
21+
self.data = bytearray(data)
22+
self.view = None
23+
24+
def __buffer__(self, flags: int) -> memoryview:
25+
self.view = memoryview(self.data)
26+
return self.view
27+
28+
29+
read_buffer(b"foo")
30+
read_buffer(memoryview(b"foo"))
31+
read_buffer(array("l", [1, 2, 3, 4, 5]))
32+
read_buffer(MyBuffer(b"foo"))
33+
read_buffer("foo") # expect-type-error
34+
read_buffer(1) # expect-type-error
35+
read_buffer(["foo"]) # expect-type-error
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
TODO:
3+
4+
Annotate the function `read_buffer`, which accepts anything that is a buffer.
5+
6+
See https://docs.python.org/3.12/reference/datamodel.html#object.__buffer__
7+
"""
8+
9+
from collections.abc import Buffer
10+
11+
12+
def read_buffer(b: Buffer):
13+
...
14+
15+
16+
## End of your code ##
17+
18+
from array import array
19+
20+
21+
class MyBuffer:
22+
def __init__(self, data: bytes):
23+
self.data = bytearray(data)
24+
self.view = None
25+
26+
def __buffer__(self, flags: int) -> memoryview:
27+
self.view = memoryview(self.data)
28+
return self.view
29+
30+
31+
read_buffer(b"foo")
32+
read_buffer(memoryview(b"foo"))
33+
read_buffer(array("l", [1, 2, 3, 4, 5]))
34+
read_buffer(MyBuffer(b"foo"))
35+
read_buffer("foo") # expect-type-error
36+
read_buffer(1) # expect-type-error
37+
read_buffer(["foo"]) # expect-type-error

0 commit comments

Comments
 (0)