Here are 10 Python code snippets demonstrating function annotations for type hints to improve code clarity and documentation:
1. Basic Type Hints for Arguments and Return Types
defadd_numbers(a:int,b:int)->int:return a + bresult =add_numbers(5,10)print(result)# Output: 15
2. Type Hinting with Optional Arguments
from typing import Optionaldefgreet(name: Optional[str]=None)->str:returnf"Hello, {name if name else'Guest'}!"print(greet())# Output: Hello, Guest!print(greet("Alice"))# Output: Hello, Alice!
3. Type Hints for Lists
from typing import Listdefcalculate_average(numbers: List[float])->float:returnsum(numbers)/len(numbers)print(calculate_average([1.5,2.5,3.0]))# Output: 2.3333333333333335
4. Type Hints for Dictionaries
5. Type Hints for Tuples
6. Type Hints for Callable (Functions as Arguments)
7. Type Hints for Iterables
8. Custom Types
9. Union for Multiple Accepted Types
10. Type Hints for Generators
These examples illustrate how type hints improve code readability and provide valuable documentation, helping developers understand the expected types of arguments and return values. Although type hints don’t enforce types at runtime, they enhance static analysis and integrate seamlessly with tools like mypy for type checking.
from typing import Callable
def execute(func: Callable[[int, int], int], x: int, y: int) -> int:
return func(x, y)
result = execute(lambda a, b: a * b, 4, 5)
print(result) # Output: 20
from typing import Iterable
def total_length(strings: Iterable[str]) -> int:
return sum(len(s) for s in strings)
print(total_length(["hello", "world"])) # Output: 10
from typing import List, TypeAlias
Vector: TypeAlias = List[float]
def scale_vector(v: Vector, scalar: float) -> Vector:
return [x * scalar for x in v]
print(scale_vector([1.0, 2.0, 3.0], 2.0)) # Output: [2.0, 4.0, 6.0]
from typing import Union
def parse_input(value: Union[str, int]) -> int:
if isinstance(value, str):
return int(value)
return value
print(parse_input("42")) # Output: 42
print(parse_input(42)) # Output: 42
from typing import Generator
def countdown(start: int) -> Generator[int, None, None]:
while start > 0:
yield start
start -= 1
for num in countdown(5):
print(num) # Output: 5, 4, 3, 2, 1