Using Type Hints to Write Better Python Functions

Using Type Hints to Write Better Python Functions
Safar Ruhi Mar 6, 2026 · 4 min read · 9 views
0

Type hints are one of the most important modern features in Python that help developers write more readable and reliable code. Introduced in Python 3.5, type hints allow you to specify the expected data types of function parameters and return values.

Although Python is dynamically typed, adding type hints makes your code easier to understand and helps tools detect potential bugs before running the program.

1. Basic Type Hints

Type hints allow you to define the type of each parameter and the return value of a function.

Example

def add(a: int, b: int) -> int:
    return a + b

a: int → parameter a should be an integer
b: int → parameter b should be an integer
-> int → function returns an integer

This does not enforce types at runtime, but it helps developers and tools understand the intended usage.

2. Type Hints for Strings, Floats, and Boolean

You can specify basic data types.

Example:

def greet(name: str) -> str:
    return f"Hello {name}"

Example with float:

def calculate_area(width: float, height: float) -> float:
    return width * height

Example with boolean:

def is_even(number: int) -> bool:
    return number % 2 == 0

3. Type Hints for Lists

You can specify the type of elements inside a list.

Example:

def calculate_average(numbers: list[float]) -> float:
    return sum(numbers) / len(numbers)

This indicates that:

numbers must be a list
each element must be a float

Example usage:

values = [10.5, 20.3, 15.7]
avg = calculate_average(values)

4. Type Hints for Dictionaries

You can specify both key type and value type.

Example:

def get_user_name(user: dict[str, str]) -> str:
    return user["name"]

Example dictionary:

user = {
    "name": "Rahul",
    "email": "rahul@email.com"
}

5. Using Optional Types

Sometimes a parameter can be None.

In such cases you can use Optional.

Example:

from typing import Optional

def find_user(user_id: int) -> Optional[str]:
    if user_id == 1:
        return "Rahul"
    return None

This tells readers that the function may return:

a string
or None

6. Using Union Types

Sometimes a variable may accept multiple types.

Example:

from typing import Union

def stringify(value: Union[int, float]) -> str:
    return str(value)

This function accepts:

integer
float

In modern Python (3.10+), you can write this shorter:

def stringify(value: int | float) -> str:
    return str(value)

7. Type Hints for Functions

You can even specify that a parameter should be a function.

Example:

from typing import Callable

def apply_operation(a: int, b: int, operation: Callable[[int, int], int]) -> int:
    return operation(a, b)

Example usage:

def add(x: int, y: int) -> int:
    return x + y

result = apply_operation(5, 3, add)

8. Type Hints for Custom Classes

Type hints work very well with classes.

Example:

class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age


def get_user_age(user: User) -> int:
    return user.age

This improves readability in large projects.

9. Benefits of Type Hints

Using type hints provides many advantages.

1. Better Code Readability

Developers can immediately understand expected inputs and outputs.

Example:

def calculate_total(price: float, tax: float) -> float:

Without reading the code, you know what the function expects.

2. Better IDE Support

Editors like:

  • VS Code
  • PyCharm

use type hints to provide:

  • autocomplete
  • error detection
  • better documentation

3. Static Type Checking

Tools like:

  • mypy
  • pyright

can detect type errors before running the program.

Example:

add("hello", "world")

A type checker will warn you because the function expects integers.

10. Best Practices for Using Type Hints

To use type hints effectively:

Always specify return types

Bad:

def add(a: int, b: int):

Better:

def add(a: int, b: int) -> int:

Use descriptive types

Instead of:

list

Prefer:

list[int]

Combine with docstrings

Type hints explain types, while docstrings explain behavior.

Example:

def calculate_discount(price: float, discount: float) -> float:
    """
    Calculate final price after applying discount.
    """
    return price * (1 - discount)

Conclusion

Type hints are a powerful tool that improves the readability, maintainability, and reliability of Python functions.

Even though Python does not enforce types strictly, adding type hints helps developers understand your code faster and prevents many common mistakes.

By combining type hints, clear function design, and proper documentation, you can write cleaner and more professional Python code.

Comments (0)

No comments yet. Be the first!

Espere Bot
Online

Chat History

👋 Hi! I'm your Espere assistant. How can I help you today?