No history yet

Basic Type Annotations

Annotating Variables

In modern Python, you can add type hints directly to your variable assignments. This makes it clear what kind of data a variable is expected to hold. The syntax is straightforward: you place a colon after the variable name, followed by the type.

# PEP 526 variable annotation syntax

user_id: int = 101
user_name: str = "Alex"
is_active: bool = True
account_balance: float = 150.75

This syntax, introduced in PEP 526, doesn't change how the code runs. Python is still dynamically typed. Instead, these annotations serve as valuable information for developers and external tools like type checkers (e.g., Mypy) and IDEs, which can use them to spot potential errors before you even run your code.

Hinting Function Types

Type hints become even more powerful when applied to functions. You can annotate both the parameters a function accepts and the value it returns. This practice makes function signatures much easier to understand without needing to read through the function's code or lengthy docstrings.

The syntax for parameters is the same as for variables. For the return value, you add an arrow -> followed by the type before the function body's colon.

def create_status_message(name: str, is_online: bool) -> str:
    """Generates a status message for a user."""
    if is_online:
        return f"{name} is currently online."
    else:
        return f"{name} is offline."

# Using the function
status = create_status_message("Alice", True)
print(status)

Think of type hints as a contract. This function promises to take a string and a boolean, and it will always return a string.

Putting It Together

Let's look at a complete example that combines variable and function annotations. Notice how the annotations create a clear, self-documenting flow of data through the program.

def calculate_discounted_price(price: float, discount_percent: int) -> float:
    """Calculates the final price after a percentage discount."""
    discount_amount = price * (discount_percent / 100)
    return price - discount_amount

# Variable annotations
original_price: float = 250.00
discount: int = 20

# The function call uses the typed variables
final_price: float = calculate_discounted_price(original_price, discount)

print(f"Final price is 💲{final_price:.2f}")

It's important to remember that these are just hints. Python's interpreter doesn't enforce them at runtime. If you were to pass a string to calculate_discounted_price, your program would still attempt to run and would likely raise a TypeError inside the function, not because of the hint itself, but because you can't perform multiplication between a string and a number. Static type checkers, however, would flag that incorrect usage before you run the code.

Quiz Questions 1/4

How do you correctly add a type hint to a variable named user_id to indicate it should hold an integer?

Quiz Questions 2/4

True or False: Python's interpreter enforces type hints at runtime, raising an error if a variable is assigned a value of the wrong type.

That's the basic syntax for adding type hints to your Python code. It's a small change that brings a lot of clarity and safety to your projects.