Type hints, introduced in Python 3.5, allow you to add static type information to your code. While Python remains a dynamically typed language (meaning types are not enforced at runtime), type hints are incredibly useful for static analysis tools, IDEs, and improving code clarity.
Why Use Type Hints?
- Catch Errors Early: Tools like Mypy can catch type-related bugs before you even run your code.
- Better Autocompletion: Your IDE can provide more accurate suggestions.
- Improved Readability: It makes your code self-documenting.
Basic Type Hinting
name: str = "Alice"
age: int = 30
is_active: bool = True
def greet(name: str) -> str:
return f"Hello, {name}"
Complex Types
For more complex types like lists, dictionaries, and tuples, you need to import them from the `typing` module.
from typing import List, Dict, Tuple, Optional
# A list of integers
ids: List[int] = [1, 2, 3]
# A dictionary with string keys and integer values
scores: Dict[str, int] = {"Alice": 95, "Bob": 88}
# A value that can be a string or None
username: Optional[str] = None
To check your code for type errors, you can install and run Mypy: `pip install mypy` and then `mypy your_script.py`.
Comments
Post a Comment