Skip to content

Commit b633129

Browse files
committed
add explicit tests for typing_extensions.Protocol
1 parent 765bb17 commit b633129

File tree

1 file changed

+45
-0
lines changed
  • crates/red_knot_python_semantic/resources/mdtest

1 file changed

+45
-0
lines changed

crates/red_knot_python_semantic/resources/mdtest/protocols.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,51 @@ Nonetheless, `Protocol` can still be used as the second argument to `issubclass(
213213
reveal_type(issubclass(MyProtocol, Protocol)) # revealed: bool
214214
```
215215

216+
## `typing.Protocol` versus `typing_extensions.Protocol`
217+
218+
`typing.Protocol` and its backport in `typing_extensions` should be treated as exactly
219+
equivalent.
220+
221+
```py
222+
import typing
223+
import typing_extensions
224+
from knot_extensions import static_assert, is_equivalent_to
225+
226+
class Foo(typing.Protocol):
227+
x: int
228+
229+
# TODO: should not error
230+
class Bar(typing_extensions.Protocol): # error: [invalid-base]
231+
x: int
232+
233+
# TODO: these should pass
234+
static_assert(typing_extensions.is_protocol(Foo)) # error: [static-assert-error]
235+
static_assert(typing_extensions.is_protocol(Bar)) # error: [static-assert-error]
236+
static_assert(is_equivalent_to(Foo, Bar)) # error: [static-assert-error]
237+
```
238+
239+
The same goes for `typing.runtime_checkable` and `typing_extensions.runtime_checkable`:
240+
241+
```py
242+
@typing_extensions.runtime_checkable
243+
class RuntimeCheckableFoo(typing.Protocol):
244+
x: int
245+
246+
# TODO: should not error
247+
@typing.runtime_checkable
248+
class RuntimeCheckableBar(typing_extensions.Protocol): # error: [invalid-base]
249+
x: int
250+
251+
# TODO: these should pass
252+
static_assert(typing_extensions.is_protocol(RuntimeCheckableFoo)) # error: [static-assert-error]
253+
static_assert(typing_extensions.is_protocol(RuntimeCheckableBar)) # error: [static-assert-error]
254+
static_assert(is_equivalent_to(RuntimeCheckableFoo, RuntimeCheckableBar)) # error: [static-assert-error]
255+
256+
# These should not error because the protocols are decorated with `@runtime_checkable`
257+
isinstance(object(), RuntimeCheckableFoo)
258+
isinstance(object(), RuntimeCheckableBar)
259+
```
260+
216261
## Calls to protocol classes
217262

218263
Neither `Protocol`, nor any protocol class, can be directly instantiated:

0 commit comments

Comments
 (0)