Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide examples of successful use of typing.Literal with dictionaries in Claudetools
    typing.Literal dictionaries Claudetools Pydantic type safety Python programming


Can you provide examples of successful use of typing.Literal with dictionaries in Claudetools


here are some examples of successfully using `typing.Literal` with dictionaries in Claudetools:

python
from typing import Literal, Dict
from pydantic import BaseModel, Field

class TodoList(BaseModel):
    todos: Dict[Literal["high", "medium", "low"], list[str]]

def print_todos(params: TodoList):
    for priority, todo_items in params.todos.items():
        print(f"Priority: {priority}")
        for todo in todo_items:
            print(f"- {todo}")

# Example usage
todos = {
    "high": ["finish report", "submit proposal"],
    "medium": ["call client", "review design"],
    "low": ["organize files", "clean desk"]
}

print_todos(TodoList(todos=todos))

In this example:

1. We define a `TodoList` model that has a `todos` field of type `Dict[Literal["high", "medium", "low"], list[str]]`. This means the keys of the dictionary must be one of the literal string values "high", "medium", or "low", and the values are lists of strings representing the todo items.

2. We implement a `print_todos` function that takes a `TodoList` parameter and prints out all the todos grouped by priority.

3. We create a sample `todos` dictionary that conforms to the specified type and pass it to the `print_todos` function.

The key points are:

- Use `typing.Literal` to specify the allowed keys for the dictionary
- Combine `typing.Literal` with `typing.Dict` in your Pydantic models
- Implement functions that accept the models with the `Dict[Literal[...], ...]` type
- Pass in dictionaries that conform to the specified type when calling the functions

This approach allows you to leverage the power of `typing.Literal` and `typing.Dict` together in your Claudetools integrations, ensuring type safety and clear documentation for your API.

Citations:
[1] https://testdriven.io/tips/c61d55d8-caa7-4ab4-b611-7356bddc0181/
[2] https://realpython.com/python-dicts/
[3] https://github.com/vatsalsaglani/claudetools
[4] https://typing.readthedocs.io/en/latest/spec/literal.html
[5] https://github.com/microsoft/python-language-server/issues/1648