Type Hints
Type hints in Python are a feature that enables developers to specify the expected data types of variables, function arguments, and return values. It was introduced in Python 3.5.
Note: Type hints are part of the
typing
module, which provides a comprehensive set of tools for type annotations.
Type hints help developers write more robust code by allowing tools like linters and IDEs to catch type-related errors before runtime.
Syntax
This is the general syntax for type hints in function annotations:
from typing import List, Dict, Union
def function_name(parameter_name: parameter_type) -> return_type:
# Function body
parameter_name
: This represents the name of the parameter that the function accepts.parameter_type
: This indicates the expected data type ofparameter_name
.return_type
: This specifies the data type of the value that the function will return.
Commonly Used Type Hints
int
,float
,str
,bool
: These are the basic data types.List[ElementType]
: This is a list containing elements ofElementType
.Dict[KeyType, ValueType]
: This is a dictionary with keys ofKeyType
and values ofValueType
.Union[Type1, Type2]
: This is a value that can be of eitherType1
orType2
.Optional[Type]
: This indicates that a value can be ofType
orNone
.
Note: Starting with Python 3.7, PEP 563 allows type annotations to be stored as strings and evaluated only when needed, optimizing runtime performance. From Python 3.10 onwards, PEP 604 introduces the
|
operator as a concise alternative toUnion
, simplifying syntax for type annotations.
Example
This is an example of a function using type hints:
from typing import List, Dict, Uniondef process_data(data: List[Dict[str, Union[int,str]]]) -> List[str]:"""Processes a list of dictionaries to extract string values.Args:(data: List[Dict[str, Union[int,str]]]): A list of dictionaries including string keys and integer or string values.PEP 604 Args:(data: List[Dict[str, int | str]]): A list of dictionaries including string keys and integer or string values as per PEP 604.Returns:List[str]: A list of string values extracted from the dictionaries."""result = []for item in data:for key, value in item.items():if isinstance(value, str):result.append(value)return result# Example usagedata = [{"name": "Alice", "age": 25},{"name": "Bob", "city": "New York"}]output = process_data(data)print(output)
The above example would output the following:
['Alice', 'Bob', 'New York']
Codebyte Example
Here is a codebyte example demonstrating the usage of type hints:
Note: While type hints enhance code clarity and facilitate static analysis during development, they do not affect how Python executes the code.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours