From 888aec9a0bf497cf32e000207d64df826f0471f5 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Wed, 16 Apr 2025 09:55:03 -0700 Subject: [PATCH 1/2] typing docs: Clarify Protocol / runtime_checkable docs - Explicitly say that isinstance/issubclass do not work on non-runtime checkable protocols. - Move the sentence "This raises TypeError when applied to a non-protocol class". It took me quite some time to decide what "this" was here: it refers to applying the decorator, not to an isinstance() call. --- Doc/library/typing.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 84f77e8f206438..948b4c1d37b927 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -2455,7 +2455,8 @@ types. See :pep:`544` for more details. Protocol classes decorated with :func:`runtime_checkable` (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their - type signatures. + type signatures. Protocol classes without this decorator cannot be used + with :func:`isinstance` and :func:`issubclass`. Protocol classes can be generic, for example:: @@ -2479,8 +2480,7 @@ types. Mark a protocol class as a runtime protocol. Such a protocol can be used with :func:`isinstance` and :func:`issubclass`. - This raises :exc:`TypeError` when applied to a non-protocol class. This - allows a simple-minded structural check, very similar to "one trick ponies" + This allows a simple-minded structural check, very similar to "one trick ponies" in :mod:`collections.abc` such as :class:`~collections.abc.Iterable`. For example:: @runtime_checkable @@ -2496,6 +2496,8 @@ types. import threading assert isinstance(threading.Thread(name='Bob'), Named) + This decorator raises :exc:`TypeError` when applied to a non-protocol class. + .. note:: :func:`!runtime_checkable` will check only the presence of the required From b08d780eceb436ee6cbdf931a8477879d5f6ddba Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Wed, 16 Apr 2025 10:38:00 -0700 Subject: [PATCH 2/2] Update Doc/library/typing.rst Co-authored-by: Alex Waygood --- Doc/library/typing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 948b4c1d37b927..a0beed4a8c77fb 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -2456,7 +2456,7 @@ types. :func:`runtime_checkable` (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes without this decorator cannot be used - with :func:`isinstance` and :func:`issubclass`. + as the second argument to :func:`isinstance` or :func:`issubclass`. Protocol classes can be generic, for example::