Introduction to Type Annotations in Python

Lesson Introduction

Welcome to learning about type annotations in Python! Understanding type annotations can significantly improve the readability and maintainability of your code. By providing explicit types for your variables and function parameters, you not only help yourself but also others who might be reading your code understand your intentions more clearly. Our goal today is to ensure you are comfortable with the syntax and usage of type annotations in Python.

What are Type Annotations?

Type annotations explicitly specify the data types of variables, function parameters, and return values. While Python is dynamically typed, meaning it doesn't require explicit data types, adding type annotations is beneficial:

  • Code Clarity: Makes your code more readable.
  • Error Prevention: Helps catch errors early with tools like mypy.
  • Documentation: Serves as documentation for your code's data types.

Basic Syntax of Type Annotations

Let's break down the basic syntax using the add function.

Without type annotations:

def add(a, b):
    return a + b

With type annotations:

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

In the function signature def add(a: int, b: int) -> int::

  • a: int indicates a should be an int.
  • b: int indicates b should be an int.
  • -> int specifies the function returns an int.

Annotating Variables

You can also annotate variables outside of functions to ensure their expected types:

if __name__ == "__main__":
    x: int = 5
    y: int = 10
    print(x, y)  # 5 10

Here, x and y are explicitly annotated as integers, clarifying their types.

Practical Example with Functions

Let's look at another example. Consider a function that greets a user:

def greet(name: str) -> str:
    return f"Hello, {name}!"
  • name: str indicates name should be a str.
  • -> str specifies the function returns a str.

Example:

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

if __name__ == "__main__":
    greeting = greet("Alice")
    print(greeting)  # Output: Hello, Alice!
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal