diff options
author | Alex Waygood <Alex.Waygood@Gmail.com> | 2023-03-23 18:18:53 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-03-23 18:18:53 +0000 |
commit | 58d2b30c012c3a9fe5ab747ae47c96af09e0fd15 (patch) | |
tree | 76c457701f61c2ff7d8c0659321251078737bc4e | |
parent | 46957091433bfa097d7ea19b177bf42a52412f2d (diff) | |
download | cpython-git-58d2b30c012c3a9fe5ab747ae47c96af09e0fd15.tar.gz |
gh-102936: typing: document performance pitfalls of protocols decorated with `@runtime_checkable` (#102937)
-rw-r--r-- | Doc/library/typing.rst | 20 |
1 files changed, 18 insertions, 2 deletions
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 80a969e633..08ffa0310f 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -1584,16 +1584,32 @@ These are not used in annotations. They are building blocks for creating generic assert isinstance(open('/some/file'), Closable) + @runtime_checkable + class Named(Protocol): + name: str + + import threading + assert isinstance(threading.Thread(name='Bob'), Named) + .. note:: - :func:`runtime_checkable` will check only the presence of the required - methods, not their type signatures. For example, :class:`ssl.SSLObject` + :func:`!runtime_checkable` will check only the presence of the required + methods or attributes, not their type signatures or types. + For example, :class:`ssl.SSLObject` is a class, therefore it passes an :func:`issubclass` check against :data:`Callable`. However, the ``ssl.SSLObject.__init__`` method exists only to raise a :exc:`TypeError` with a more informative message, therefore making it impossible to call (instantiate) :class:`ssl.SSLObject`. + .. note:: + + An :func:`isinstance` check against a runtime-checkable protocol can be + surprisingly slow compared to an ``isinstance()`` check against + a non-protocol class. Consider using alternative idioms such as + :func:`hasattr` calls for structural checks in performance-sensitive + code. + .. versionadded:: 3.8 Other special directives |