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 @@ -1582,16 +1582,32 @@ These are not used in annotations. They are building blocks for creating generic
1582
1582
1583
1583
assert isinstance(open('/some/file'), Closable)
1584
1584
1585
+ @runtime_checkable
1586
+ class Named(Protocol):
1587
+ name: str
1588
+
1589
+ import threading
1590
+ assert isinstance(threading.Thread(name='Bob'), Named)
1591
+
1585
1592
.. note ::
1586
1593
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 `
1589
1597
is a class, therefore it passes an :func: `issubclass `
1590
1598
check against :data: `Callable `. However, the
1591
1599
``ssl.SSLObject.__init__ `` method exists only to raise a
1592
1600
:exc: `TypeError ` with a more informative message, therefore making
1593
1601
it impossible to call (instantiate) :class: `ssl.SSLObject `.
1594
1602
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
+
1595
1611
.. versionadded :: 3.8
1596
1612
1597
1613
Other special directives
You can’t perform that action at this time.
0 commit comments