PYTHON FOR AI • LESSON 6

Type Hints

Type hints allow you to describe what kind of data a variable, function parameter, or function return value is expected to contain. They make Python code easier to understand, maintain, and debug.

CORE IDEA

Type hints tell humans and tools what type of data your code expects.

Python is still dynamically typed. Type hints do not force Python to reject a wrong type at runtime. Their main purpose is to make your code clearer and allow tools such as editors and type checkers to detect possible problems.

01

What Are Type Hints?

A type hint tells us what type of value we expect.

Without a type hint:

name = "Raj"

age = 29

We can add type hints:

name: str = "Raj"

age: int = 29

Here:

  • str means string.
  • int means integer.
02

Why Use Type Hints?

Type hints become more useful as your application becomes larger.

Consider:

def calculate_price(price, quantity):
    return price * quantity

Someone reading this function has to guess what price and quantity should be.

With type hints:

def calculate_price(
    price: float,
    quantity: int
) -> float:

    return price * quantity

Now the function clearly communicates its expected inputs and output.

03

Common Python Types

Some of the most common types are:

str      → text
int      → whole numbers
float    → decimal numbers
bool     → True / False
list     → collection of values
dict     → key-value data
tuple    → fixed collection
set      → unique values

Examples:

name: str = "AI"

age: int = 29

price: float = 99.99

active: bool = True

scores: list = [80, 90, 95]

user: dict = {
    "name": "Raj",
    "age": 29
}
04

Type Hints for Function Parameters

Function parameters can have type hints.

def greet(name: str):

    print(f"Hello {name}")


greet("Raj")

This tells the reader that name is expected to be a string.

Another example:

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

    return a + b


result = add_numbers(10, 20)

print(result)
30
05

Type Hints for Return Values

You can also specify what type a function is expected to return.

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

    return a + b

The arrow:

-> int

means that the function is expected to return an integer.

Example with a string:

def get_name() -> str:

    return "Raj"
06

Type Hints for Lists

You can specify what type of values a list should contain.

scores: list[int] = [
    80,
    90,
    95
]

This communicates that the list is expected to contain integers.

A list of strings:

names: list[str] = [
    "Raj",
    "John",
    "Sarah"
]

This is especially useful when working with collections of AI-related data.

07

Type Hints for Dictionaries

Dictionaries contain keys and values, so we can describe their types as well.

user: dict[str, str] = {
    "name": "Raj",
    "country": "India"
}

Here both the keys and values are strings.

Another example:

scores: dict[str, int] = {
    "math": 90,
    "python": 95
}

The keys are strings and the values are integers.

08

Optional Values

Sometimes a function may return a value or None.

For example:

def find_user(
    user_id: int
) -> str | None:

    if user_id == 1:

        return "Raj"

    return None

The return type:

str | None

means the function can return either a string or None.

09

Type Aliases

If you repeatedly use a complicated type, you can give it a meaningful name.

UserData = dict[str, str]


user: UserData = {
    "name": "Raj",
    "country": "India"
}

This makes complex code easier to read.

10

Type Hints for API Data

Type hints are particularly useful in API-based applications.

For example:

def get_product(
    product_id: int
) -> dict:

    return {
        "id": product_id,
        "name": "AI Laptop",
        "price": 1200
    }

Now we know that:

  • product_id should be an integer.
  • The function returns a dictionary.
11

Type Hints in an AI Application

Imagine an AI application that sends a prompt to an AI service.

def generate_response(
    prompt: str
) -> str:

    response = "AI response"

    return response

The function clearly tells us:

Input
  ↓
prompt: str
  ↓
AI processing
  ↓
return: str
  ↓
Output

This becomes increasingly valuable when an application has many functions and API integrations.

12

Type Hints with an API Client

We can improve the API client from the previous lesson.

class APIClient:

    def get_product(
        self,
        product_id: int
    ) -> dict:

        return {
            "id": product_id,
            "name": "AI Laptop"
        }

Now another developer can immediately understand how the method should be used.

product = client.get_product(10)

print(product["name"])
13

Important: Type Hints Do Not Enforce Types

This is one of the most important things to understand.

Python does not automatically stop you from passing the wrong type.

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

    return a + b


result = add_numbers(
    "10",
    "20"
)

Python does not automatically reject the strings just because the function says int.

Therefore, type hints are primarily for:

  • Code readability
  • Developer understanding
  • Editor support
  • Static type checking
14

Type Hints and Your Editor

Modern editors such as VS Code can use type hints to provide better autocomplete and detect possible mistakes.

def get_name() -> str:

    return "Raj"


name = get_name()

name.upper()

Because the editor knows that name is a string, it can provide string-specific suggestions.

15

Static Type Checking

Tools such as MyPy can analyze your Python code before you run it.

For example:

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

    return a + b


result = add(
    "10",
    "20"
)

A static type checker can identify that strings are being passed where integers were expected.

This helps catch mistakes earlier.

16

Good Type Hint Practices

  • Add type hints to important function parameters.
  • Add return types to functions.
  • Use meaningful types instead of vague ones.
  • Use collection types such as list[str] when useful.
  • Use str | None when a value may be missing.
  • Use type hints consistently across larger projects.
  • Do not assume type hints automatically validate data.
17

Mini Project — Typed AI Functions

Create a small set of typed functions for an AI application.

def create_prompt(
    question: str
) -> str:

    return f"Answer this question: {question}"


def generate_response(
    prompt: str
) -> str:

    return "This is an AI response."


def calculate_score(
    score: float,
    total: float
) -> float:

    return score / total


question: str = "What is Python?"

prompt = create_prompt(question)

response = generate_response(prompt)

percentage = calculate_score(
    90.0,
    100.0
)


print(prompt)
print(response)
print(percentage)
Answer this question: What is Python?
This is an AI response.
0.9

Notice how the types make each function's purpose immediately clear.

18

What You Learned

  • What type hints are
  • Why type hints improve code readability
  • Type hints for variables
  • Type hints for function parameters
  • Return type hints
  • Type hints for lists
  • Type hints for dictionaries
  • Optional values
  • Type aliases
  • Type hints in API clients
  • Type hints in AI applications
  • Why type hints do not automatically enforce types
  • How editors and static type checkers use type hints
KEY TAKEAWAY

Type hints make your code communicate its expectations.

They tell developers and development tools what kind of data functions expect and return. They do not replace validation, but they make larger Python and AI applications much easier to understand and maintain.