DEV Community

qing
qing

Posted on

Python Type Hints: Write Better Code with Type Annotations

Python Type Hints: Write Better Code with Type Annotations

Type hints make your Python code more readable, maintainable, and catch bugs before runtime. Here's a practical guide to using them effectively.

Complete Code Example

from typing import List, Dict, Optional, Union, Tuple, Any
from typing import Callable, Generator, TypeVar
from dataclasses import dataclass

# Basic type hints
def greet(name: str, times: int = 1) -> str:
    return f"Hello, {name}! " * times

# Collections
def process_items(items: List[int]) -> Dict[str, int]:
    return {"sum": sum(items), "count": len(items)}

# Optional (can be None)
def find_user(user_id: int) -> Optional[str]:
    users = {1: "Alice", 2: "Bob"}
    return users.get(user_id)  # Returns str or None

# Union (multiple types)
def parse_value(v: Union[str, int, float]) -> float:
    return float(v)

# Generic TypeVar
T = TypeVar("T")
def first_item(items: List[T]) -> Optional[T]:
    return items[0] if items else None

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

result = apply(lambda x: x * 2, 5)  # 10

# Dataclass with types
@dataclass
class User:
    name: str
    age: int
    email: Optional[str] = None
    tags: List[str] = None

    def __post_init__(self):
        if self.tags is None:
            self.tags = []

user = User("Alice", 30, "alice@example.com")
print(user)  # User(name='Alice', age=30, ...)
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Pro Tips

  • Run mypy to catch type errors before runtime: pip install mypy
  • Type hints don't affect runtime performance
  • Start adding type hints to function signatures first

Why This Matters

Understanding these Python features will help you write more:

  • โœ… Readable and maintainable code
  • โœ… Memory-efficient applications
  • โœ… Pythonic, idiomatic solutions

Summary

Mastering Python's built-in features is key to becoming a better developer. Practice these examples in your own projects, and you'll quickly see the benefits.


Found this helpful? Follow me for more Python tutorials and tips! ๐Ÿ

Follow for more Python content!


๐Ÿ“ง Get my FREE Python Cheatsheet โ†’ Follow me on Dev.to and drop a comment below โ€” I'll DM you the cheatsheet directly!

๐Ÿ 50+ essential Python patterns, one-liners, and best practices for everyday development. Free for all readers.


๐Ÿ› ๏ธ Recommended Tool

If you found this useful, check out Content Creator Ultimate Bundle (Save 33%) โ€” $29.99 and designed for developers like you.

Get instant access to our best-selling AI Dev Boost, HTML Landing Page Templates, AI Prompts for Developers, and Python Automation Scripts Pack, perfect for content creators and marketers looking to elevate their game. This bundle is a must-have for anyone looking to create stunning content, build high-converting landing pages, and drive real results. With these tools, you'll be able to create engaging content, build beautiful landing pages, and boost your online presence.


ๅ–œๆฌข่ฟ™็ฏ‡ๆ–‡็ซ ๏ผŸๅ…ณๆณจ่Žทๅ–ๆ›ดๅคšPython่‡ชๅŠจๅŒ–ๅ†…ๅฎน๏ผ

Top comments (0)