File tree 1 file changed +18
-2
lines changed
1 file changed +18
-2
lines changed Original file line number Diff line number Diff line change @@ -1584,16 +1584,32 @@ These are not used in annotations. They are building blocks for creating generic
1584
1584
1585
1585
assert isinstance(open('/some/file'), Closable)
1586
1586
1587
+ @runtime_checkable
1588
+ class Named(Protocol):
1589
+ name: str
1590
+
1591
+ import threading
1592
+ assert isinstance(threading.Thread(name='Bob'), Named)
1593
+
1587
1594
.. note ::
1588
1595
1589
- :func: `runtime_checkable ` will check only the presence of the required
1590
- methods, not their type signatures. For example, :class: `ssl.SSLObject `
1596
+ :func: `!runtime_checkable ` will check only the presence of the required
1597
+ methods or attributes, not their type signatures or types.
1598
+ For example, :class: `ssl.SSLObject `
1591
1599
is a class, therefore it passes an :func: `issubclass `
1592
1600
check against :data: `Callable `. However, the
1593
1601
``ssl.SSLObject.__init__ `` method exists only to raise a
1594
1602
:exc: `TypeError ` with a more informative message, therefore making
1595
1603
it impossible to call (instantiate) :class: `ssl.SSLObject `.
1596
1604
1605
+ .. note ::
1606
+
1607
+ An :func: `isinstance ` check against a runtime-checkable protocol can be
1608
+ surprisingly slow compared to an ``isinstance() `` check against
1609
+ a non-protocol class. Consider using alternative idioms such as
1610
+ :func: `hasattr ` calls for structural checks in performance-sensitive
1611
+ code.
1612
+
1597
1613
.. versionadded :: 3.8
1598
1614
1599
1615
Other special directives
You can’t perform that action at this time.
0 commit comments