Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I combine typing.Literal with other type hints in Claudetools
    typing.Literal Claudetools type hints custom types pydantic type definitions Python typing


Can I combine typing.Literal with other type hints in Claudetools


Yes, you can absolutely combine `typing.Literal` with other type hints in Claudetools. Here are a few examples:

Using `Literal` with custom types

python
from typing import Literal
from pydantic import BaseModel, Field

class Color(str):
    RED = "red"
    GREEN = "green" 
    BLUE = "blue"

ColorLiteral = Literal[Color.RED, Color.GREEN, Color.BLUE]

class PaintJob(BaseModel):
    color: ColorLiteral
    coats: Literal[1, 2, 3]

def paint_car(params: PaintJob):
    print(f"Painting car {params.color} with {params.coats} coats.")

In this example, we define a custom `Color` class and use `Literal` to create a `ColorLiteral` type that can only accept the specific color values. We then use this `ColorLiteral` type in the `PaintJob` model, along with a `Literal` type for the number of coats.

Using `Literal` with built-in types

python
from typing import Literal
from pydantic import BaseModel, Field

class TodoItem(BaseModel):
    text: str
    priority: Literal["low", "medium", "high"]

def add_todo(params: TodoItem):
    print(f"Adding todo: {params.text} (priority: {params.priority})")

Here, we use `Literal` to constrain the `priority` field of the `TodoItem` model to only accept the string values "low", "medium", or "high".

Combining `Literal` with other type annotations

python
from typing import Literal, List, Optional
from pydantic import BaseModel, Field

class Book(BaseModel):
    title: str
    author: str
    genre: Literal["fiction", "non-fiction", "biography"]
    tags: Optional[List[Literal["adventure", "romance", "historical"]]]

def catalog_book(params: Book):
    print(f"Book: {params.title} by {params.author} ({params.genre})")
    if params.tags:
        print(f"Tags: {', '.join(params.tags)}")

In this example, we use `Literal` to constrain the `genre` field to a set of predefined values, and we also use `Literal` to define the allowed tags for the `tags` field, which is a list.

By combining `Literal` with other type annotations, you can create very precise and expressive type definitions for your Claudetools functions, ensuring that only valid input data is accepted and providing clear documentation for users of your API.

Citations:
[1] https://docs.python.org/3/library/typing.html
[2] https://testdriven.io/tips/c61d55d8-caa7-4ab4-b611-7356bddc0181/
[3] https://typing.readthedocs.io/en/latest/spec/literal.html
[4] https://github.com/microsoft/python-language-server/issues/1648
[5] https://github.com/sphinx-doc/sphinx/issues/9195