Hone logo
Hone
Problems

Static Type Checking with mypy

Mypy is a static type checker for Python that can help you catch type-related errors before runtime. This challenge focuses on integrating mypy into an existing Python project and ensuring that the code adheres to type annotations, ultimately improving code reliability and maintainability. You'll be provided with a Python file containing some code and asked to add type hints and fix any mypy errors to make the code type-safe.

Problem Description

You are given a Python file (example.py) containing a few functions and classes. Your task is to:

  1. Add Type Hints: Add appropriate type hints to all function arguments, return values, and class attributes. Consider the intended data types and use Python's type hinting syntax (e.g., def my_function(arg: int) -> str:).
  2. Run mypy: Execute mypy on the example.py file.
  3. Fix Errors: Address any type errors reported by mypy. This may involve changing type hints, modifying function signatures, or adjusting the code logic to ensure type consistency.
  4. Ensure No Errors: Repeat steps 2 and 3 until mypy reports no errors. The final code should be fully type-checked and free of mypy errors.

The goal is to make the code as type-safe as possible, leveraging mypy to identify potential issues early in the development process.

Examples

Example 1:

Let's say example.py initially contains:

def add(x, y):
  return x + y

After adding type hints and running mypy, you might modify it to:

def add(x: int, y: int) -> int:
  return x + y

Mypy would then report no errors.

Example 2:

Suppose example.py contains:

class Person:
  name = "Alice"

  def greet(self):
    return "Hello, " + self.name

After adding type hints and running mypy, you might modify it to:

class Person:
  name: str = "Alice"

  def greet(self) -> str:
    return "Hello, " + self.name

Mypy would then report no errors.

Constraints

  • You must use Python 3.7 or higher to ensure compatibility with type hinting features.
  • The provided example.py file will contain a mix of functions and classes.
  • You are expected to use standard Python type hints (e.g., int, str, List, Dict, Tuple, Optional, Union, Any).
  • The solution should be executable and produce no runtime errors after mypy checks pass.
  • The code should be readable and well-formatted.

Notes

  • Install mypy using pip install mypy.
  • Run mypy on the file using the command mypy example.py.
  • Pay close attention to the error messages provided by mypy. They will guide you in identifying and fixing type errors.
  • Consider using Optional and Union when a variable or function return value can be of multiple types or None.
  • Don't be afraid to refactor the code slightly to improve type safety, as long as the functionality remains the same.
  • The initial example.py file is provided below. Your solution is to modify this file to pass mypy checks.
# example.py
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

def process_data(data):
    total = 0
    for item in data:
        total += item
    return total

def get_user_info(user_id):
    # Simulate fetching user info from a database
    if user_id == 1:
        return {"id": 1, "name": "John Doe"}
    else:
        return None

def format_user_info(user):
    if user:
        return f"User ID: {user['id']}, Name: {user['name']}"
    else:
        return "User not found"
Loading editor...
python