Overloaded Functions with @typing.overload
`@overload` lets you define multiple type signatures for a single function when return types depend dynamically on input argument types 🤹.
from typing import overload, Union
@overload
def process(data: int) -> int: ...
@overload
def process(data: str) -> str: ...
def process(data: Union[int, str]) -> Union[int, str]:
return data * 2
print(process(5)) # Inferred as int (10) 🤹
print(process("abc")) # Inferred as str ('abcabc') 🤹
# 97. Overloaded Functions with @typing.overload `@overload` lets you define multiple type signatures for a single function when return types depend dynamically on input argument types 🤹. ```python from typing import overload, Union @overload def process(data: int) -> int: ... @overload def process(data: str) -> str: ... def process(data: Union[int, str]) -> Union[int, str]: return data * 2 print(process(5)) # Inferred as int (10) 🤹 print(process("abc")) # Inferred as str ('abcabc') 🤹 ``` The `@overload` signatures contain only `...` (an ellipsis body) and are ignored at runtime. The single un-decorated implementation handles the real logic! 🤹 --- ### Question What goes inside the body of an `@overload` decorated function stub? 🧠- [ ] a. `...` (an ellipsis) or `pass` 🤹 - [ ] b. The full compiled C implementation - [ ] c. An explicit `return NotImplemented` - [ ] d. A call to `sys.exit()` --- ### Challenge Write an overloaded function `combine`: `@overload def combine(a: int) -> int: ...`, `@overload def combine(a: str) -> str: ...`. Implement `def combine(a): return a + a`. Print `combine(21)` and `combine('Go')`. 🎯 <details> <summary>Solution</summary> ```python from typing import overload @overload def combine(a: int) -> int: ... @overload def combine(a: str) -> str: ... def combine(a): return a + a print(combine(21)) print(combine("Go")) ``` </details>