Skip to content

Commit d24ddf8

Browse files
committed
pretalk
1 parent 3cab7ce commit d24ddf8

7 files changed

+706
-0
lines changed

README.md

+52
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,55 @@
11
# protocol_examples
22

33
Examples using `typing.Protocol` from PEP 544
4+
5+
## Notes
6+
7+
### Classic Example: a "file-like object"
8+
9+
From [_PEP 333 – Python Web Server Gateway Interface v1.0_](https://peps.python.org/pep-0333/) (2003):
10+
11+
12+
> To be considered “file-like”, the object supplied by the application
13+
must have a `read()` method that takes an optional size argument.
14+
15+
The words "file-like" (or "file like") appear with similar implied meaning
16+
in the Python 3.12 distribution:
17+
18+
- 148 times in the documentation;
19+
- 92 times in code comments (`.py` or `.c` source files).
20+
21+
Also, 30 times across 21 PEPs (100, 214, 258, 282, 305, 310, 333, 368, 400, 441, 444, 578, 680, 691, 3116, 3119, 3143, 3145, 3154, 3156, 3333).
22+
23+
24+
Definition in `Lib/wsgiref/types.py`:
25+
26+
```python
27+
class _Readable(Protocol):
28+
def read(self, size: int = ..., /) -> bytes: ...
29+
```
30+
31+
### Examples as of 2024-05-23
32+
33+
`typing.Protocol` definitions found with `ripgrep`:
34+
35+
```shell
36+
rg "Protocol\)" -g '*.pyi' | sort
37+
```
38+
39+
- 120 definitions on `typeshed/stdlib` (Python standard library)
40+
- 134 definitions on `typeshed/stubs` (external packages)
41+
42+
43+
44+
### Cases to study
45+
46+
- `importlib/resources/abc.py`: `class Traversable(Protocol)`
47+
with several abstract and concrete methods, looks like an ABC but derives from `typing.Protocol`
48+
49+
50+
### Not `typing.Protocol`
51+
52+
- `asyncio/protocols.py`: defines classes `BaseProtocol`, `Protocol` etc. for network protocols
53+
54+
55+

ast_hacks/test_experiments.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from ast import parse, Module, FunctionDef
2+
import inspect
3+
4+
5+
def double_any[T](x: T) -> T:
6+
return x * 2
7+
8+
9+
def test_double_any():
10+
tree = parse(inspect.getsource(double_any))
11+
match tree:
12+
case Module(body=[FunctionDef(type_params=tps)]):
13+
tv=tps[0]
14+
15+
assert tv.name == 'T'

0 commit comments

Comments
 (0)