Claudetools can handle type validation for dictionaries using `typing.Literal` by leveraging Pydantic's type validation capabilities. Here's an example of how you can define a dictionary with `Literal` keys and validate it using 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}")
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` in the Pydantic model, Claudetools ensures that only valid priority values are used as keys in the dictionary. If you try to pass in a dictionary with keys that don't match the specified `Literal` types, Pydantic will raise a validation error.
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://typing.readthedocs.io/en/latest/spec/literal.html
[2] https://testdriven.io/tips/c61d55d8-caa7-4ab4-b611-7356bddc0181/
[3] https://help.sap.com/doc/saphelp_nw73ehp1/7.31.19/en-US/0d/e90c05e3024b309eb539c9a7b923a1/content.htm
[4] https://github.com/tiangolo/sqlmodel/issues/57
[5] https://github.com/vatsalsaglani/claudetools