idiombench / Python /train /3.8 /protocol /modern_27.py
SwashBuckler001's picture
IdiomBench (part 10)
c6ed2d8 verified
Raw History Blame Contribute Delete
414 Bytes
class P(Protocol):
x: int
class C:
def initialize(self) -> None:
self.x = 0
c = C()
isinstance(c, P) # False
c.initialize()
isinstance(c, P) # True
def f(x: Union[P, int]) -> None:
if isinstance(x, P):
# Static type of x is P here.
...
else:
# Static type of x is int, but can be other type at runtime...
print(x + 1)
f(C()) # ...causing a TypeError.