← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Type Hints

Topic: Type System

Advertisement

Introduction

Type hints annotate variables, function parameters, and return types for better code clarity.

Basic Type Hints

def greet(name: str) -> str:
    return f"Hello, {name}"

age: int = 25
prices: list[float] = [1.99, 2.99]

Complex Types

from typing import List, Dict, Tuple, Optional, Union

# Multiple types
def process(x: Union[int, float]) -> Optional[str]:
    pass

# Generic types
def sum_list(nums: List[float]) -> float:
    return sum(nums)

# Dictionary with types
def word_count(texts: List[str]) -> Dict[str, int]:
    return {t: len(t) for t in texts}

# Tuple
def coordinates() -> Tuple[float, float]:
    return (1.0, 2.0)

Callable Types

from typing import Callable

def apply(func: Callable[[int], int], value: int) -> int:
    return func(value)

# With multiple arguments
def execute(func: Callable[[int, str], bool], a: int, b: str) -> bool:
    return func(a, b)

Practice Problems

  1. Add type hints to a function
  2. Create TypedDict for complex data
  3. Use Protocol for duck typing
  4. Type a decorator
  5. Define generics with TypeVar

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →