Tutorials Logic, IN info@tutorialslogic.com

Python Type Hints: Annotations, Optional Values, and Aliases

Typing Basics

Type hints are annotations that describe the kind of value a function expects or returns.

Python still runs dynamically, but type hints help editors, reviewers, and static checkers catch mistakes earlier.

Use type hints to make function boundaries clear, not to make every tiny variable look complicated.

Function Annotations

Function annotations show parameter and return types directly in the function definition.

  • Use parameter hints for values callers must provide.
  • Use return hints to show what the function gives back.

Annotate a Function

Annotate a Function
def format_total(amount: float, currency: str = "INR") -> str:
    return f"{currency} {amount:.2f}"

print(format_total(499.5))
Output
INR 499.50

The hints say amount should be a float, currency should be text, and the result should be text.

Collection Types

Collection hints explain what kind of values a list, tuple, set, or dictionary should contain.

  • Use list[str] for a list of strings.
  • Use dict[str, int] for string keys and integer values.
  • Use tuple[str, int] for a fixed two-part tuple.

Hint a Dictionary

Hint a Dictionary
def total_marks(scores: dict[str, int]) -> int:
    return sum(scores.values())

marks = {"math": 88, "science": 91}
print(total_marks(marks))
Output
179

The function expects a dictionary where subject names are strings and marks are integers.

Optional Values

Some values can be present or missing. Type hints can show that a value may be None.

  • Use str | None for text that may be missing.
  • Check for None before calling string methods.

Handle Missing Email

Handle Missing Email
def display_email(email: str | None) -> str:
    if email is None:
        return "No email added"
    return email.lower()

print(display_email(None))
Output
No email added

The hint makes it obvious that None is allowed and must be handled.

Type Aliases

A type alias gives a readable name to a repeated or complex type shape.

  • Use aliases for records and nested structures that appear in multiple functions.
  • Keep aliases near the code that owns the data shape.

Behavior Protocols

A Protocol describes the operations a value must support without requiring inheritance from one base class. Static checkers can accept any object with the compatible members, which matches Python duck typing while making the expected behavior visible.

Require a Close Method

Require a Close Method
from typing import Protocol

class Closable(Protocol):
    def close(self) -> None: ...

def finish(resource: Closable) -> None:
    resource.close()

The annotation supports static checking; add @runtime_checkable only when an actual isinstance() check is required.

Generic Values

A type variable preserves a relationship between input and output types. It is more precise than returning object or Any because the checker can infer the result from the supplied collection.

Return the First Item Type

Return the First Item Type
from typing import TypeVar

T = TypeVar("T")

def first(items: list[T]) -> T:
    if not items:
        raise ValueError("items must not be empty")
    return items[0]

print(first([10, 20, 30]))
Output
10
Skill check

Can You Read Type Hints?

5 checks
  • Add type hints to public functions first.
  • Use collection hints when list or dictionary contents matter.
  • Handle None explicitly when a value can be missing.
  • Keep hints simple enough for the team to read.
  • Use editor or checker feedback as guidance, not as a substitute for tests.

Type Hint Confusion

  • Thinking hints enforce types at runtime

    Type hints help tools and readers. Python still runs dynamically unless you add validation.
  • Hinting unclear code instead of simplifying it

    Make the function shape clear first, then add annotations.
  • Using vague Any everywhere

    Use specific hints where the expected value shape is known.

Try this next

Add Hints to a Function

0 of 3 completed

  1. Add parameter and return hints to a price total function.
  2. Annotate a variable that stores a list of scores.
  3. Call a hinted function with the wrong type and explain what Python does at runtime.

Questions About Type Hint

No. Python still runs dynamically. Type hints mainly help tools, editors, documentation, and code review.

No. Start with function parameters, returns, and confusing data structures. Obvious local variables rarely need hints.

It means the value can be a string or None, so your code should handle both cases.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.