Python Intermediate and Advanced

Python Intermediate_005: Type Hinting in Python

codeaddict 2025. 2. 8. 01:47

When writing Python code, you often need to make your code more readable and maintainable, especially for larger projects. This is where type hinting becomes essential. Type hints help you specify the expected types of variables, function arguments, and return values. Let’s explore how to use type hints effectively with simple examples.

Why Use Type Hints?

Type hints help:

  1. Improve code readability.
  2. Catch type-related errors during development.
  3. Provide better autocompletion and type checking in IDEs.

Basic Type Hints

Here’s how to annotate variable types and function signatures:

# Variable type hints
name: str = "Alice"
age: int = 30
is_active: bool = True

# Function with type hints
def greet(name: str) -> str:
    return f"Hello, {name}!"
print(greet("Bob"))

Explanation:

  • name: str: Indicates that name is a string.
  • age: int: Indicates that age is an integer.
  • def greet(name: str) -> str: Specifies that the greet function takes a string argument and returns a string.

Type Hints with Collections

You can annotate lists, dictionaries, and other collections using the List and Dict types from the typing module.

from typing import List, Dict

# List of integers
numbers: List[int] = [1, 2, 3, 4]
# Dictionary with string keys and integer values
data: Dict[str, int] = {"apples": 5, "oranges": 3}
print(numbers)
print(data)

Explanation:

  • List[int]: Specifies that numbers is a list containing integers.
  • Dict[str, int]: Indicates that data is a dictionary with string keys and integer values.

Type Hints for Functions with Multiple Arguments

You can use type hints to specify types for multiple arguments.

from typing import List

def calculate_sum(numbers: List[int]) -> int:
    return sum(numbers)
result = calculate_sum([10, 20, 30])
print(f"Sum: {result}")

Explanation:

  1. numbers: List[int]: The function expects a list of integers.
  2. -> int: The function returns an integer.

Using Optional Types

Sometimes, a variable or function argument can be optional. Use Optional to indicate this.

from typing import Optional

def greet(name: Optional[str] = None) -> str:
    if name:
        return f"Hello, {name}!"
    return "Hello, Stranger!"
print(greet())
print(greet("Alice"))

Explanation:

  • Optional[str]: Indicates that name can be either a string or None.
  • The default value of None allows the argument to be optional.