Skip to main content

Command Palette

Search for a command to run...

Typing your Data in Python

Clear your code with Type Hints

Updated
4 min readView as Markdown
Typing your Data in Python
A

I'm an Engineer, really into coding and making technology work for business.

Obsessed with reading, writing and continuous learning.

Introduction

Did you ever looked at your code and wished you had a clearer idea of what types of data you're working with? That's where type hints come in.

Type hints can make your Python code easier to read and maintain.

Plus, when you combine them with a tool like mypy, you can catch errors before they sneak into your code.

Let's dive into how type hints work and why they’re super helpful.

What Are Type Hints?

Type hints allow you to annotate your code with information about the expected types of variables, function parameters, and return values. While Python itself won’t enforce these types at runtime, tools like mypy can check them for you during development.

Basic Usage of Type Hints

Let's see an example:

def hello(name: str) -> str:
    """Returns a greeting message."""
    return f"Hello, {name}!"

# Here's a variable with a type hint
age: int = 25

print(hello("Alice"))  # Output: Hello, Alice!

In this example, hello expects a name of type str and returns a str. The age variable is annotated as an int.

Type Hints for Collections

You can also specify types for elements within collections like lists, tuples, and dictionaries using the typing module:

from typing import List, Dict, Tuple

# List of strings
names: List[str] = ["Alice", "Bob", "Charlie"]

# Dictionary with string keys and integer values
scores: Dict[str, int] = {"Alice": 95, "Bob": 80}

# Tuple containing a string and an integer
person: Tuple[str, int] = ("Alice", 25)

These annotations ensure that the elements within your collections are of the expected types.

Advanced Type Hints

The typing module includes several advanced features for more complex type annotations:

  • Union: Indicates a variable can be one of several types.

  • Optional: Shorthand for Union[X, None].

  • Any: Accepts any type.

from typing import Union, Optional, Any

# A variable that can be an int or a float
number: Union[int, float] = 3.14

# A variable that can be an int or None
optional_number: Optional[int] = None

# A variable that can be any type
anything: Any = "Hello"

Type Hints in Classes

You can use type hints in class definitions to annotate attributes and methods:

class Person:
    def __init__(self, name: str, age: int) -> None:
        self.name: str = name
        self.age: int = age

    def birthday(self) -> None:
        self.age += 1

# Let's create a person and celebrate their birthday
person = Person(name="Alice", age=25)
person.birthday()
print(person.age)  # Output: 26

Here, Person has attributes name and age, both with type annotations. The birthday method updates the age attribute (of type int).

Integrating mypy for Static Type Checking

To boost type hints, use a static type checker like mypy. It checks your code against the type hints you’ve provided and reports any inconsistencies.

Installingmypy:

pip install mypy

Let's look at an example:

# your_script.py
def add_numbers(a: int, b: int) -> int:
    return a + b

print(add_numbers(2, 3))  # This is fine
print(add_numbers("2", "3"))  # This will cause a type error

Run mypy on this script:

mypy your_script.py

mypy will report:

your_script.py:5: error: Argument 1 to "add_numbers" has incompatible type "str"; expected "int"
your_script.py:5: error: Argument 2 to "add_numbers" has incompatible type "str"; expected "int"This feedback helps you catch and correct type errors early, making your code more reliable.

This feedback helps you catch and correct type errors early, making your code more reliable.

Tips for Using Type Hints and mypy

  1. Start Small: Begin by adding type hints to a few key functions and variables. Expand as you get more comfortable.

  2. Run Regular Checks: Use mypy regularly to catch type errors during development.

  3. Keep It Updated: Ensure your type hints stay accurate as your code evolves. Inaccurate type hints can be misleading and prone to errors.

  4. Use IDEs: Use an IDE that supports type hints and integrates with mypy for improved code completion and error checking.

Conclusion

Typing in Python makes your code clearer and helps catch bugs before they become problems.

Combine type hints with a static type checker like mypy and improve your coding experience.

Start with type hints in your next project and see how they can improve your code.

Happy coding!

Python Programming

Part 6 of 17

Dive into the dynamic world of Python programming and data. Learn various advanced techniques to master Python and its applications in data management, software design, and system behavior.

Up next

Using Configuration Files for Dynamic System Behavior

A practical example from my MarketPipe project