You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`abc.ABC` enforce the inheritance of abstract methods, requiring subclasses to implement them.
359
+
`typing.Protocol` is only for typing, allowing for structural subtyping without enforcing inheritance.
360
+
361
+
```python title="typing.Protocol"
362
+
from typing import Protocol
363
+
364
+
classShape(Protocol):
365
+
defarea(self) -> float: ...
366
+
367
+
# no class Circle(Shape) here
368
+
classCircle:
369
+
def__init__(self, r: float) -> None:
370
+
self.r = r
371
+
372
+
defarea(self) -> float:
373
+
return3.14159*self.r *self.r
374
+
375
+
defprint_area(s: Shape) -> None:
376
+
print(s.area())
377
+
378
+
c = Circle(10)
379
+
# as c has area() method, it matches Shape protocol, MyPy is happy with that.
380
+
print_area(c) # ✅ Circle matches Shape structurally
381
+
```
382
+
356
383
## Callable and Protocol
357
384
358
385
[From MyPy](https://mypy.readthedocs.io/en/stable/protocols.html#callback-protocols): We can use [Protocols](https://typing.python.org/en/latest/spec/protocol.html) to define [callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable) types with a special [**call**](https://docs.python.org/3/reference/datamodel.html#object.__call__) member:
@@ -545,11 +572,47 @@ concat(1, 2) # Error!
545
572
546
573
## Overloading
547
574
548
-
Use [@overload](https://mypy.readthedocs.io/en/stable/more_types.html#function-overloading) to let type checkers know that a function can accept different types of arguments and return different types based on those arguments.
575
+
Use [@overload](https://mypy.readthedocs.io/en/stable/more_types.html#function-overloading) to let type checkers know that a function can accept different types of arguments and return different types based on those arguments.
549
576
550
577
!!! note "If there are multiple equally good matching variants (overloaded functions), mypy will select the variant that was defined first."
551
578
Put always the finest overloaded function at first: https://mypy.readthedocs.io/en/stable/more_types.html#type-checking-the-variants
552
579
580
+
### Overloading example
581
+
582
+
```python title="Overloading __getitem__() method with Python 3.12 syntax"
0 commit comments