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 @@ -1350,16 +1350,32 @@ These are not used in annotations. They are building blocks for creating generic
1350
1350
1351
1351
assert isinstance(open('/some/file'), Closable)
1352
1352
1353
+ @runtime_checkable
1354
+ class Named(Protocol):
1355
+ name: str
1356
+
1357
+ import threading
1358
+ assert isinstance(threading.Thread(name='Bob'), Named)
1359
+
1353
1360
.. note ::
1354
1361
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 `
1357
1365
is a class, therefore it passes an :func: `issubclass `
1358
1366
check against :data: `Callable `. However, the
1359
1367
``ssl.SSLObject.__init__ `` method exists only to raise a
1360
1368
:exc: `TypeError ` with a more informative message, therefore making
1361
1369
it impossible to call (instantiate) :class: `ssl.SSLObject `.
1362
1370
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
+
1363
1379
.. versionadded :: 3.8
1364
1380
1365
1381
Other special directives
You can’t perform that action at this time.