Python Type Hints: Syntax, Meaning, and Real Use in Functions

Python type hints let you write down the kinds of values a function expects and returns. They do not change how Python runs your code, but they make your intent clearer for readers, editors, and type checkers. This article shows how function annotations work, how to read them, where they help, and where they can mislead you.

Difficulty: Beginner

Helpful to know first: basic Python functions, variables, and lists or dictionaries.

How Python Type Hints Describe Function Inputs and Outputs

Type hints are labels you attach to function parameters and return values. They tell humans and tools what kind of values your function is designed to accept, but Python itself still runs the function at runtime even if the values do not match the hints.

Here is the smallest useful example:

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

print(greet("Ada"))  # Output: Hello, Ada!

The name: str part says the parameter should be a string. The -> str part says the function should return a string. Python does not enforce that at runtime, but a type checker can warn you if you pass the wrong kind of value.

Type hints are written as annotations. You will also hear them called function annotations or typing annotations.

How to Read the Most Common Python Type Hint Syntax

Python uses a small set of symbols again and again in function hints. Once you learn these pieces, most function signatures become easy to read.

Single values with built-in types

Use a built-in type name when a function expects one value of that type.

Python
def square(number: int) -> int:
    return number * number

print(square(6))  # Output: 36

This means the function expects an integer and returns an integer. The code still works with any value that supports multiplication in the way the function uses it, but the hint describes the intended input.

Multiple values with list and dict

For containers, put the element type inside square brackets. Python 3.12 lets you write these forms directly with the built-in generic types.

Python
def total_points(scores: list[int]) -> int:
    return sum(scores)

print(total_points([10, 15, 5]))  # Output: 30

The hint list[int] means a list whose items should be integers. Similarly, dict[str, int] means a dictionary with string keys and integer values.

Optional values and unions

Sometimes a parameter can be one of several types. Use the | operator to say that a value may be either type.

Python
def format_name(middle_name: str | None) -> str:
    if middle_name is None:
        return "No middle name"
    return middle_name.upper()

print(format_name("Marie"))  # Output: MARIE
print(format_name(None))      # Output: No middle name

Here, the function accepts either a string or None. This is one of the most common real uses of type hints, because optional values appear often in user input and configuration.

How Python Type Hints Work at Runtime

Type hints are part of the function object. Python stores them in the function’s annotations, but it does not automatically reject a mismatched argument or a wrong return value.

Python
def repeat(text: str, count: int) -> str:
    return text * count

print(repeat("ha", 3))  # Output: hahaha
print(repeat("ha", "3"))  # Output: ha3

The second call does not raise a type error from Python itself. It produces a string because Python repeats a string when you multiply it by another value that behaves like an integer? No. In this case, string multiplication by another string is not supported, so the code raises a TypeError at runtime. The type hint would help a checker catch the problem before you run the program.

This is the key idea: type hints document intent, while Python still enforces only the rules of the operations your code actually performs.

What the interpreter stores in annotations

You can inspect the annotations directly. That is useful when you want to understand how Python remembers the hints.

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

print(area.__annotations__)  # Output: {'width': <class 'float'>, 'height': <class 'float'>, 'return': <class 'float'>}

The annotations are stored as data. Tools can read them, but your code still needs to handle invalid values if it may receive them.

How to Use Type Hints in Real Functions

Type hints become most useful when a function has more than one input, or when the function works with nested structures. They make the function’s contract easier to understand without reading every line of code.

Parsing and validating user input

Suppose a function receives a list of strings from a form, file, or command-line arguments. A hint can show that the function expects raw text and returns cleaned data.

Python
def parse_ages(values: list[str]) -> list[int]:
    return [int(value) for value in values]

print(parse_ages(["12", "18", "21"]))  # Output: [12, 18, 21]

This hint is useful because the function changes the data type. It receives strings and returns integers, which is easy to miss when reading quickly.

Returning structured data

When a function returns several related fields, type hints help describe the shape of that data.

Python
def build_profile(name: str, age: int) -> dict[str, int | str]:
    return {"name": name, "age": age}

print(build_profile("Ava", 16))  # Output: {'name': 'Ava', 'age': 16}

The return type says the dictionary keys are strings and the values are either integers or strings. That is accurate here because the profile stores both kinds of values.

Making helper functions easier to reuse

Hints are especially helpful for small helper functions that may be reused in many places. They make the intended input and output clear without extra comments.

Python
def join_words(words: list[str], separator: str) -> str:
    return separator.join(words)

print(join_words(["red", "green", "blue"], ", "))  # Output: red, green, blue

Because the hints are close to the function body, a reader can understand the function faster and spot mismatches sooner.

How Type Hints Behave with Copies, Mutability, and Default Values

Type hints describe what you intend to pass, but they do not change how objects behave. Mutable objects such as lists and dictionaries can still be shared, updated, and reused in ways that surprise beginners.

For example, a hint like list[int] does not make a copy of the list. If two variables point to the same list, changes through one name are visible through the other.

Python
def add_bonus(scores: list[int]) -> None:
    scores.append(10)

class_scores = [7, 8]
add_bonus(class_scores)
print(class_scores)  # Output: [7, 8, 10]

The hint does not protect the caller from mutation. It only describes the expected kind of object.

If a function should not change a list, say so in the function name, docstring, or by using a non-mutating pattern inside the function.

Default values still matter

Type hints do not fix the classic mutable default pitfall. This is one of the most important places where beginners misunderstand annotations.

Python
def add_item(item: str, items: list[str] = []) -> list[str]:
    items.append(item)
    return items

This function has a valid type hint, but the default list is shared across calls. That is a runtime behavior issue, not a typing issue.

The safer pattern uses None and creates a new list inside the function.

Python
def add_item(item: str, items: list[str] | None = None) -> list[str]:
    if items is None:
        items = []
    items.append(item)
    return items

Type hints can describe the parameter better here, but the fix comes from changing the default value pattern.

Predict the Output

These short snippets test common misunderstandings about function annotations. Read the code carefully, then check the answer.

Predict the Output: annotations do not enforce runtime types

Python
def double(value: int) -> int:
    return value * 2

print(double("7"))

What happens?

Show answer

This prints 77, not 14, and Python does not stop the call because of the annotation. The parameter is hinted as int, but the actual argument is a string. String multiplication by 2 repeats the string, so the function returns "77".

Predict the Output: mutating a value through a hinted list

Python
def grow(items: list[int]) -> None:
    items.append(4)

numbers = [1, 2, 3]
grow(numbers)
print(numbers)

What does this print?

Show answer

This prints [1, 2, 3, 4]. The function changes the same list object that numbers refers to. The type hint does not copy the list or protect it from mutation.

Find the Bug

Here is a function that looks reasonable, but it has a subtle bug. Find the problem before reading the fix.

Python
def add_tag(tag: str, tags: list[str] = []) -> list[str]:
    tags.append(tag)
    return tags

print(add_tag("python"))
print(add_tag("typing"))
Show answer

The bug is the mutable default list. The same list is reused every time the function is called, so the second call keeps the item from the first call.

Fixed code:

Python
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

print(add_tag("python"))
print(add_tag("typing"))

The corrected version works because a fresh list is created each time the caller does not supply one.

Common Mistakes with Python Type Hints

Using a type hint as a runtime check

Beginners often think annotations automatically validate input. They do not.

Problem: The function hint says age should be an integer, but the code still receives a string and fails later when it tries to add numbers.

Python
def next_year(age: int) -> int:
    return age + 1

print(next_year("12"))

Fix: Convert the value before calling the function, or validate it inside the function if text input is expected.

Python
def next_year(age: int) -> int:
    return age + 1

age_text = "12"
print(next_year(int(age_text)))

The corrected version works because the function receives the type it was designed to use.

Forgetting that annotations do not copy mutable values

A list hint does not create a new list. If you reuse the same object, later changes still affect it.

Problem: The function mutates the list passed in, so the caller sees the change.

Python
def mark_done(tasks: list[str]) -> None:
    tasks.append("done")

todo = ["study", "sleep"]
mark_done(todo)
print(todo)

Fix: Make a copy inside the function if you want to keep the original list unchanged.

Python
def mark_done(tasks: list[str]) -> list[str]:
    new_tasks = tasks.copy()
    new_tasks.append("done")
    return new_tasks

todo = ["study", "sleep"]
print(mark_done(todo))

The corrected version works because the function changes a separate list.

Using the wrong container hint for the data shape

A hint should match the real structure of the object. If the structure is different, readers and tools get the wrong message.

Problem: The code returns pairs, but the annotation says the function returns a dictionary.

Python
def pairs() -> dict[str, int]:
    return [("a", 1), ("b", 2)]

Fix: Use a matching type such as list[tuple[str, int]] if the function returns a list of pairs.

Python
def pairs() -> list[tuple[str, int]]:
    return [("a", 1), ("b", 2)]

The corrected version works because the annotation now matches the actual return value.

How Python Type Hints Compare with No Hints and Runtime Checks

Type hints are useful, but they are not the same as runtime validation. The best choice depends on whether you want documentation, editor help, or actual input checking.

ApproachWhat it doesBest forWhat it does not do
Type hintsDescribe expected types for tools and readersReadable function signatures, editor assistance, type checkingDo not enforce types at runtime
No hintsLeave types unstatedSmall scripts and throwaway codeGive less guidance to readers and tools
Runtime checksValidate values while the program runsUser input, public APIs, strict data validationDo not help static analysis by themselves

Use type hints when the shape of the data matters and you want tools to help you. Use runtime checks when bad input is likely and the program must reject it safely.

Type hints versus docstrings

Docstrings explain behavior in plain language. Type hints show the structure directly in the function signature. They work well together, but they solve different problems.

Python
def discount(price: float, rate: float) -> float:
    """Return the price after applying a discount rate."""
    return price * (1 - rate)

The signature tells you the input and output types. The docstring tells you what the function means.

When to Use Python Type Hints and When Something Else Is Better

Type hints are a good default for most functions in larger Python codebases. They are especially useful when a function is called from many places, when data moves through several layers, or when an editor or type checker can catch mistakes early.

Use type hints when...Use something else when...
You want clearer function contractsYou only need a quick one-off script
You are passing structured data between functionsThe code is so small that the extra detail adds no value
You want editor completion and static checksYou need runtime validation of user input
You are documenting a public helper functionThe real problem is missing validation, not missing annotations

For validation-heavy code, use explicit checks in the function body. For very dynamic code, hints can become too broad or too complex and may not be worth the cost. For most ordinary functions, though, hints improve readability with very little overhead.

Common situations where hints help most

Type hints are especially valuable for functions that receive lists, dictionaries, optional values, or mixed data. They also help when a function returns a value that is not obvious from the name alone.

Python
def find_active_user(users: list[dict[str, str]]) -> dict[str, str] | None:
    for user in users:
        if user["status"] == "active":
            return user
    return None

That signature tells a lot about the function before you even read its body. It says what the input looks like, what the function searches for, and why the return value may be missing.

Predict the Output

These snippets focus on misunderstandings that appear often in beginner code: annotations do not copy values, and function behavior still follows Python's normal rules.

Interview Questions About Python Type Hints

Do Python type hints change how code runs?

No. Python stores hints as annotations, but it does not enforce them automatically. They are mainly for documentation, editors, and type checkers.

Why use None in a type hint?

Use None when a value may be missing. A hint like str | None means the parameter or return value can be a string or no value at all.

Why is list[int] better than just list?

list[int] tells readers and tools what kind of items belong in the list. A plain list says only that the value is a list, not what it contains.

Try It Yourself

Write a function that takes a list of prices as floats and returns the total after adding tax.

  • The function should be named total_with_tax.
  • It should accept prices: list[float] and tax_rate: float.
  • It should return a float.
  • Call it with [10.0, 15.0, 5.0] and 0.1.
  • The expected output is 33.0.

Hint: add the prices first, then multiply by 1 + tax_rate.

Show solution
Python
def total_with_tax(prices: list[float], tax_rate: float) -> float:
    subtotal = sum(prices)
    return subtotal * (1 + tax_rate)

print(total_with_tax([10.0, 15.0, 5.0], 0.1))  # Output: 33.0

Summary

  • Python type hints describe the expected input and output types of a function.
  • Hints improve readability and help editors and type checkers find mistakes early.
  • Python does not enforce hints at runtime, so incorrect values can still reach the function.
  • Container hints like list[int] and dict[str, int] describe the shape of your data.
  • None and the | operator are common for optional values.
  • Type hints do not fix runtime problems like mutable defaults or shared lists.

Next, learn how Python's typing tools describe complex function signatures such as Callable, TypeVar, and Protocol.