לדלג לתוכן

6.10 typing הרצאה

מודול typing

  • מאפשר לנו לעשות type-hinting לכל סוג של אובייקט.
  • הריצו pip install typing
    from typing import List, Tuple
    
    def greet(name: str) -> str:
        return f"Hello, {name}"
    
    def add_numbers(a: int, b: int) -> int:
        return a + b
    
    def process_data(data: List[str]) -> Tuple[int, str]:
        length = len(data)
        concatenated = ', '.join(data)
        return length, concatenated
    
  • אפשר לראות שהפונקציה process_data מקבלת רשימה של מחרוזות, ומחזירה טאפל של מחרוזות.
    from typing import Optional, Union
    
    def square_number(number: Union[int, float]) -> Optional[float]:
        if isinstance(number, (int, float)):
            return number ** 2
        else:
            return None
    
  • אנחנו יכולים להשתמש בOptional וב - Union כדי לעשות פונקציה שיכולה לקבל מספר של type-ים ולהחזיר מספר של type-ים.
    from typing import List, Tuple
    
    Coordinate = Tuple[float, float]
    Path = List[Coordinate]
    
    def calculate_distance(path: Path) -> float:
        total_distance = 0.0
        for i in range(len(path) - 1):
            x1, y1 = path[i]
            x2, y2 = path[i + 1]
            distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
            total_distance += distance
        return total_distance
    
  • אפשר גם לתת שם לtype-ים מיוחדים שאנחנו בונים.
    from typing import Callable
    
    def apply_operation(x: int, y: int, operation: Callable[[int, int], int]) -> int:
        return operation(x, y)
    
    def multiply(a: int, b: int) -> int:
        return a * b
    
    result = apply_operation(5, 3, multiply)
    
  • הטייפ Callable מאפשר לנו לעשות טייפ מסוג פונקציה
    from typing import List, Tuple, TypeVar
    
    T = TypeVar('T')
    
    def reverse_items(items: List[T]) -> List[T]:
        return items[::-1]
    
    reversed_list = reverse_items([1, 2, 3, 4])
    
  • טייפ גנרי - הפונקציה reverse_items יכולה לקבל רשימה עם כל סוג של איבר, ולהחזיר רשימה עם כל סוג של איבר.