Python Type Casting & Type Hinting
Type casting converts data from one type to another, while type hinting provides explicit hints about what data types variables, parameters, and function return values are expected to hold.
Python Type Casting
Python is dynamically typed, but it requires explicit conversion when operating on incompatible types. Type casting falls into two categories: Implicit (handled automatically) and Explicit (handled manually using built-in functions).
Implicit Type Conversion
Python automatically converts one data type to another to prevent data loss (e.g., converting an integer to a float during arithmetic).
num_int = 10
num_float = 2.5
# Python automatically converts num_int to float before addition
result = num_int + num_float
print(result) # Output: 12.5
print(type(result)) # Output:
Explicit Type Conversion
You manually convert a value using built-in constructor functions: int(), float(), str(), bool(), list(), tuple(), set(), and dict().
# String to Integer / Float
str_num = "100"
converted_int = int(str_num) # 100
converted_float = float(str_num) # 100.0
# Number to String
val = 42
str_val = str(val) # "42"
# Sequence Casting
items_tuple = (1, 2, 2, 3)
unique_set = set(items_tuple) # {1, 2, 3}
items_list = list(unique_set) # [1, 2, 3]
# Boolean Conversion (Truthy vs Falsy)
# Empty structures, 0, None, and False evaluate to False; others evaluate to True.
print(bool(0)) # False
print(bool("")) # False
print(bool([1, 2])) # True
Python Type Hinting
Introduced in PEP 484 (Python 3.5+), type hints do not enforce types at runtime—Python remains dynamically typed. Instead, they improve code readability, enable static analysis (via tools like mypy), and enhance IDE auto-completion.
Basic Variable Annotations
name: str = "Alice"
age: int = 30
height: float = 5.8
is_active: bool = True
Function Annotations
Specify expected parameter types and the return type using ->.
def calculate_total(price: float, quantity: int) -> float:
return price * quantity
total: float = calculate_total(19.99, 3)
Collection Types
Python 3.9+ allows using standard collections (list, dict, tuple, set) directly for type hints.
# Generic collections (Python 3.9+)
# A list that should only hold integers (whole numbers)
scores: list[int] = [90, 85, 88]
# A dictionary with text (str) keys and text (str) values
user_roles: dict[str, str] = {"admin": "Alice", "editor": "Bob"}
# A tuple containing exactly two decimal numbers (floats)
coordinates: tuple[float, float] = (37.7749, -122.4194)
# A set that should only hold integers
unique_ids: set[int] = {101, 102, 103}
Advanced Type Hints (typing module)
For complex scenarios, use the built-in typing module or modern syntax additions.
Union Types & Optional Values (Python 3.10+)
Use | to denote multiple allowable types, or to mark a value that can be None.
# Python 3.10+ syntax:
def process_id(user_id: int | str) -> str:
return f"User ID: {user_id}"
# Optional parameter (equivalent to int | None)
def find_user(user_id: int) -> str | None:
if user_id == 1:
return "Alice"
return None
(For Python 3.7–3.9, import Union and Optional from typing: Union[int, str] and Optional[str])
Callable (Functions as Arguments)
from typing import Callable
# Expects a function taking two ints and returning an int
def apply_operation(a: int, b: int, operation: Callable[[int, int], int]) -> int:
return operation(a, b)
def add(x: int, y: int) -> int:
return x + y
result = apply_operation(5, 3, add) # 8
Any & Type Aliases
from typing import Any
# Any disables type checking for a variable
data: Any = "Could be anything"
# Type Alias for readability
Vector = list[float]
def scale_vector(v: Vector, factor: float) -> Vector:
return [x * factor for x in v]
Comparison Summary
| Feature | Type Casting | Type Hinting |
|---|---|---|
| Purpose | Converts data from one type to another | Documents expected types for static analysis |
| Execution Time | Occurs at runtime | Evaluated at parse time (ignored at runtime) |
| Error Handling | Raises ValueError or TypeError if conversion fails |
Does not raise runtime errors (requires linter like mypy) |
| Syntax Example | x = int("10") |
x: int = 10 |