8000 gh-102936: typing: document performance pitfalls of protocols decorat… · python/cpython@6c667d0 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6c667d0

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 <Alex.Waygood@Gmail.com>
1 parent 4531fd0 commit 6c667d0

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
@@ -1350,16 +1350,32 @@ These are not used in annotations. They are building blocks for creating generic
13501350

13511351
assert isinstance(open('/some/file'), Closable)
13521352

1353+
@runtime_checkable
1354+
class Named(Protocol):
1355+
name: str
1356+
1357+
import threading
1358+
assert isinstance(threading.Thread(name='Bob'), Named)
1359+
13531360
.. note::
13541361

1355-
:func:`runtime_checkable` will check only the presence of the required
1356-
methods, not their type signatures. For example, :class:`ssl.SSLObject`
1362+
:func:`!runtime_checkable` will check only the presence of the required
1363+
methods or attributes, not their type signatures or types.
1364+
For example, :class:`ssl.SSLObject`
13571365
is a class, therefore it passes an :func:`issubclass`
13581366
check against :data:`Callable`. However, the
13591367
``ssl.SSLObject.__init__`` method exists only to raise a
13601368
:exc:`TypeError` with a more informative message, therefore making
13611369
it impossible to call (instantiate) :class:`ssl.SSLObject`.
13621370

1371+
.. note::
1372+
1373+
An :func:`isinstance` check against a runtime-checkable protocol can be
1374+
surprisingly slow compared to an ``isinstance()`` check against
1375+
a non-protocol class. Consider using alternative idioms such as
1376+
:func:`hasattr` calls for structural checks in performance-sensitive
1377+
code.
1378+
13631379
.. versionadded:: 3.8
13641380

13651381
Other special directives

0 commit comments

Comments
 (0)
0