Skip to content

Commit e2924c0

Browse files
gh-102936: typing: document performance pitfalls of protocols decorated with @runtime_checkable (GH-102937)
(cherry picked from commit 58d2b30) Co-authored-by: Alex Waygood <[email protected]>
1 parent 1645a40 commit e2924c0

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

Doc/library/typing.rst

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1582,16 +1582,32 @@ These are not used in annotations. They are building blocks for creating generic
15821582

15831583
assert isinstance(open('/some/file'), Closable)
15841584

1585+
@runtime_checkable
1586+
class Named(Protocol):
1587+
name: str
1588+
1589+
import threading
1590+
assert isinstance(threading.Thread(name='Bob'), Named)
1591+
15851592
.. note::
15861593

1587-
:func:`runtime_checkable` will check only the presence of the required
1588-
methods, not their type signatures. For example, :class:`ssl.SSLObject`
1594+
:func:`!runtime_checkable` will check only the presence of the required
1595+
methods or attributes, not their type signatures or types.
1596+
For example, :class:`ssl.SSLObject`
15891597
is a class, therefore it passes an :func:`issubclass`
15901598
check against :data:`Callable`. However, the
15911599
``ssl.SSLObject.__init__`` method exists only to raise a
15921600
:exc:`TypeError` with a more informative message, therefore making
15931601
it impossible to call (instantiate) :class:`ssl.SSLObject`.
15941602

1603+
.. note::
1604+
1605+
An :func:`isinstance` check against a runtime-checkable protocol can be
1606+
surprisingly slow compared to an ``isinstance()`` check against
1607+
a non-protocol class. Consider using alternative idioms such as
1608+
:func:`hasattr` calls for structural checks in performance-sensitive
1609+
code.
1610+
15951611
.. versionadded:: 3.8
15961612

15971613
Other special directives

0 commit comments

Comments
 (0)