Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Is it possible to use typing.Literal with typing.Dict in Claudetools


Is it possible to use typing.Literal with typing.Dict in Claudetools


Yes, you can absolutely use `typing.Literal` with `typing.Dict` in Claudetools. Here's an example:

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}")

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. When calling the `print_todos` function, we can pass in a dictionary that conforms to the specified type:

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

print_todos(TodoList(todos=todos))

This will output:


Priority: high
- finish report
- submit proposal
Priority: medium 
- call client
- review design
Priority: low
- organize files
- clean desk

By using `typing.Literal` with `typing.Dict`, you can precisely specify the allowed keys for the dictionary, ensuring that only valid priority values are used. This provides type safety and clear documentation for your Claudetools functions.

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.

Citations:
[1] https://typing.readthedocs.io/en/latest/spec/literal.html
[2] https://testdriven.io/tips/c61d55d8-caa7-4ab4-b611-7356bddc0181/
[3] https://github.com/vatsalsaglani/claudetools
[4] https://github.com/sphinx-doc/sphinx/issues/9195
[5] https://github.com/microsoft/pylance-release/issues/715