Type hints in Python are used to indicate the expected types of variables, function parameters, and return values. They are a feature introduced in Python 3.5 as part of PEP 484. Here's how you can use type hints:
Function Annotations:
To add type hints to function parameters and return values, you use a colon :
followed by the type. For example:
def greet(name: str) -> str: return f"Hello, {name}!"
In this example, name
is expected to be a str
, and the function is expected to return a str
.
Variable Annotations:
You can also add type hints to variables:
age: int = 30
Here, age
is annotated as an int
.
Collections:
For collections like lists, tuples, and dictionaries, you use the typing
module introduced in Python 3.5:
from typing import List, Tuple, Dict numbers: List[int] = [1, 2, 3] coordinates: Tuple[int, int] = (10, 20) person: Dict[str, str] = {"name": "Alice", "city": "Wonderland"}
Union and Optional:
You can specify that a variable or parameter can be one of several types using Union
or indicate that it can be None
using Optional
:
from typing import Union, Optional def process(value: Union[int, str]) -> int: if isinstance(value, str): return int(value) return value def say_hello(name: Optional[str] = None) -> str: return f"Hello, {name or 'World'}!"
Generic Types:
Type hints can also be used with generics to specify the type of elements in a collection:
from typing import List, TypeVar T = TypeVar('T') def first(items: List[T]) -> T: return items[0]
By using type hints, developers can make their code more understandable and self-documenting, which can be helpful for static type checking tools.
Type hints in Python offer several benefits:
mypy
allow for static type checking, which can catch type-related errors before runtime. This is particularly useful in large codebases where manually checking types can be error-prone and time-consuming.Type hints improve code readability and maintainability in the following ways:
def add(a: int, b: int) -> int:
, they immediately know that the function takes two integers and returns an integer. This clarity reduces the cognitive load required to understand the code.Here are some examples demonstrating the usage of type hints in Python functions and variables:
Function with Type Hints:
from typing import List, Tuple def calculate_average(numbers: List[float]) -> float: if not numbers: return 0.0 return sum(numbers) / len(numbers) def format_coordinates(x: float, y: float) -> str: return f"({x:.2f}, {y:.2f})" def process_data(data: Tuple[int, str, float]) -> str: id, name, value = data return f"ID: {id}, Name: {name}, Value: {value:.2f}"
Variables with Type Hints:
from typing import List, Dict, Optional scores: List[int] = [85, 90, 78] student_grades: Dict[str, float] = {"Alice": 3.5, "Bob": 3.8} favorite_color: Optional[str] = None
Combining Type Hints with Default Values:
from typing import List def greet(name: str = "World") -> str: return f"Hello, {name}!" def sum_numbers(numbers: List[int] = []) -> int: return sum(numbers)
Using Union and Generic Types:
from typing import Union, List, TypeVar T = TypeVar('T') def first_element(items: List[T]) -> T: return items[0] def process_value(value: Union[int, float, str]) -> str: return str(value)
These examples demonstrate how type hints can be applied to different elements of Python code, enhancing readability and maintainability.
The above is the detailed content of How do you use type hints in Python?. For more information, please follow other related articles on the PHP Chinese website!