Python type hints are a way to annotate the types of variables, function arguments, and return values in Python code. They are used to provide additional information about the expected data types, making the code more readable and enabling static type checkers to catch potential type-related errors.
Type hints were introduced in Python 3.5, and their usage has become more popular with the advent of Python 3.7 and above, where they have been further enhanced.
Here are some common type hinting annotations in Python:
1. Basic Type Hints:
int
: Integerfloat
: Floating-point numberbool
: Boolean value (True or False)str
: Stringbytes
: Bytes
2. Type Hinting Variables: You can annotate variables like this:
name: str = "John"
age: int = 30
3. Type Hinting Function Arguments:
def greet(name: str) -> str:
return f"Hello, {name}"
4. Type Hinting Function Return Values:
def add(a: int, b: int) -> int:
return a + b
5. Optional Type Hints: You can indicate optional arguments or return values using Optional
from the typing
module:
from typing import Optional
def get_name(prefix: str, suffix: Optional[str] = None) -> str:
if suffix is None:
return prefix
else:
return prefix + " " + suffix
6. Type Hinting Collections: You can hint lists, tuples, and dictionaries:
from typing import List, Tuple, Dict
def process_data(data: List[int]) -> Dict[str, int]:
# Process the data and return a dictionary
pass
7. Union Type Hints: If a variable or argument can have multiple types, you can use the Union
type hint:
from typing import Union
def square_root(num: Union[int, float]) -> float:
return num ** 0.5
Type hints do not affect the runtime behavior of the code, but they provide useful information for developers and tools that perform static type checking, like mypy
. Static type checking helps catch type-related errors before running the code, making it easier to maintain and understand Python projects.
Python type hints example
Here’s a simple example that demonstrates the use of Python-type hints:
def calculate_area(length: float, width: float) -> float:
"""
Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The area of the rectangle.
"""
area = length * width
return area
# Function call with type-checked arguments
length_input = 5.5
width_input = 3.2
result = calculate_area(length_input, width_input)
print(f"The area of the rectangle is: {result}")
Output:
In this example, we have a function calculate_area
, which takes two arguments, length
and width
, both type float
. The function returns a value of type float
, representing the area of the rectangle.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.