Understanding Python Type Hints

Type hints are a feature introduced in Python 3.5+ that allow specifying expected types for variables, function parameters, and return values. They do not change the dynamic typing nature of Python but can enhance code readability, improve IDE support, and help catch potential errors early with static analysis tools like <span>mypy</span>.

Basic Syntax

1. Variable Type Hints

To specify a type for a variable, the format is <span>variable_name: type = value</span>:

name: str = "拾光"  # String
age: int = 18        # Integer
height: float = 1.75 # Float
is_student: bool = False  # Boolean

2. Function Parameter and Return Type Hints

  • • Function parameters:<span>def function_name(parameter: type, ...)</span>
  • • Return value:<span>def function_name(...) -> return_type</span>
def greet(name: str) -&gt; str:
    """Greet a person with the specified name"""
    return f"Hello, {name}!"

def add(a: int, b: int) -&gt; int:
    """Return the sum of two integers"""
    return a + b

3. Types (List, Tuple, Dictionary, etc.)

Generic types need to be imported from the <span>typing</span> module (from Python 3.9+, built-in containers can be used directly with brackets):

# Python 3.9+ syntax
from typing import List, Tuple, Dict, Set  # Compatible with older versions, can be omitted in 3.9+

# List (all elements are int)
numbers: list[int] = [1, 2, 3]
# Tuple
person: tuple[str, int] = ("拾光", 18)  # (Name, Age)
# Dictionary
scores: dict[str, int] = {"math": 90, "english": 85}
# Set
hobbies: set[str] = {"reading", "coding"}

4. Optional Types (<span>Optional</span>)

Indicates that a variable/parameter can be of a specified type or <span>None</span>

from typing import Optional

def find_user(user_id: int) -&gt; Optional[str]:
    """Find a user, return username if found, otherwise return None"""
    if user_id == 1:
        return "拾光"
    return None  # Allow returning None

Equivalent to <span>Union[type, None]</span>

5. Union Types (<span>Union</span>)

Indicates that a variable/parameter can be one of several types

from typing import Union

def print_id(user_id: Union[int, str]) -&gt; None:
    """Accepts user ID as either an integer or string and prints it"""
    print(f"User ID: {user_id}")

print_id(123)    # Valid (int)
print_id("u456") # Valid (str)

6. Function Types (<span>Callable</span>)

Indicates that a parameter or return value is a function

from typing import Callable

def calculate(a: int, b: int, func: Callable[[int, int], int]) -&gt; int:
    """Calculate the result of a and b using the passed function"""
    return func(a, b)

def multiply(x: int, y: int) -&gt; int:
    return x * y

result = calculate(3, 4, multiply)  # Pass function as parameter
print(result)  # Output: 12

7. Custom Types

Aliases can be defined for complex types

from typing import List, Tuple

# Define type alias: User information (Name, Age, Hobbies list)
UserInfo = Tuple[str, int, List[str]]

def get_user() -&gt; UserInfo:
    return ("Charlie", 30, ["hiking", "photography"])

Static Type Checking (<span>mypy</span>)

<span>mypy</span> is a commonly used static checking tool that can detect type mismatches before runtime:

# pip install mypy
def add(a: int, b: int) -&gt; int:
    return a + b

result = add("1", 2)  # Error: First argument should be int, actual passed str

Run check:

mypy demo.py

Output error message:

error: Argument 1 to "add" has incompatible type "str"; expected "int"

Type hints are an important tool for engineering Python code, and their proper use can significantly improve code quality and maintainability.

#Python #python type hints

Leave a Comment