Back to Rules

Using type hints in Python for better code quality

Code

from typing import List, Dict, Optional

def process_items(items: List[str]) -> Dict[str, int]:
    return {item: len(item) for item in items}

def find_user(user_id: int) -> Optional[Dict[str, str]]:
    # Simulating database lookup
    users = {
        1: {"name": "John", "email": "john@example.com"},
        2: {"name": "Jane", "email": "jane@example.com"}
    }
    return users.get(user_id)

# Example usage
items = ["apple", "banana", "cherry"]
result = process_items(items)
print(result)  # {'apple': 5, 'banana': 6, 'cherry': 6}

user = find_user(1)
if user:
    print(f"Found user: {user['name']}")
python
Posted by Tejashwa Tiwari1/29/2024