Python Type Hints

Python type hints let you describe the expected type of a variable, function parameter, or return value. They make code easier to read and help editors, linters, and type checkers find mistakes before runtime.

Type hints do not make Python a statically typed language. Python still runs dynamically. The hints mainly guide tools and developers, so you can document intent without changing normal runtime behavior.

Basic Type Hint Syntax

Use a colon after a variable or parameter name, followed by the expected type. Use an arrow to describe a function's return type.

Example:

# Annotate variables with expected types.
student_name: str = "Aarav"
score: int = 92
is_passed: bool = True

# Annotate function parameters and return value.
def greet(name: str) -> str:
    return f"Hello, {name}"
Hint Meaning
str Text value
int Whole number
float Decimal number
bool True or False value
list[str] List of strings
dict[str, int] Dictionary with string keys and integer values

Type Hint Function Parameters

Add type hints to parameters when the function expects a specific kind of value. This helps users call the function correctly.

Example:

def calculate_total(price: float, quantity: int) -> float:
    # Return the final amount for one item type.
    return price * quantity

print(calculate_total(249.50, 3))

Use Collection Type Hints

Modern Python lets you write built-in collection types directly, such as list[str] and dict[str, int]. This syntax is concise and easy to read.

Example:

def average_score(scores: list[int]) -> float:
    # Divide the total score by the number of items.
    return sum(scores) / len(scores)

marks = [82, 91, 76]
print(average_score(marks))

Allow More Than One Type

Use the union operator | when a value can have more than one type. This is common when a value may be missing.

Example:

def format_discount(discount: int | None) -> str:
    # None means no discount was set.
    if discount is None:
        return "No discount"
    return f"{discount}% off"

print(format_discount(None))
print(format_discount(15))

Create Type Aliases

A type alias gives a readable name to a longer type hint. Use aliases when the same type appears in many functions.

Example:

# Create a readable name for a dictionary shape.
StudentMarks = dict[str, int]

def top_subject(marks: StudentMarks) -> str:
    # Return the subject with the highest mark.
    return max(marks, key=marks.get)

print(top_subject({"Math": 88, "English": 93}))

Use TypedDict for Dictionary Structure

Use TypedDict when a dictionary should contain specific keys with specific value types. This makes dictionary-based data easier to understand.

Example:

from typing import TypedDict

class UserProfile(TypedDict):
    name: str
    email: str
    age: int

def show_user(user: UserProfile) -> str:
    # Read known keys from the typed dictionary.
    return f"{user['name']} <{user['email']}>"

print(show_user({"name": "Emma", "email": "[email protected]", "age": 28}))

What Type Hints Do Not Do

Type hints are not automatic runtime validation. Python will not reject the wrong type unless your code or another library checks it.

Example:

def double_count(count: int) -> int:
    return count * 2

# Python runs this, even though the argument is a string.
print(double_count("5"))

The result is 55 because string multiplication repeats the string. A type checker can warn you before running the code.

Practical Guidelines

  • Add hints to public functions first because they are read by other developers.
  • Use simple built-in types whenever they explain enough.
  • Use | None only when None is a valid value.
  • Avoid very complex hints when they make beginner code harder to read.
  • Run a type checker if you want tools to enforce the annotations.

Tip: Good type hints should make code easier to understand. If a hint becomes harder to read than the code itself, simplify the design or use a type alias.

Conclusion

Python type hints improve code clarity without removing Python's flexibility. Use them for variables, functions, collections, optional values, and structured dictionaries so tools and developers can understand your code faster.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram