4

The OpenAI Python types define a Batch class with a status field:

class Batch(BaseModel):
    id: str

    # ...

    status: Literal[
        "validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"
    ]
    """The current status of the batch."""

I'd like to re-use the Literal[...] type hint from the status field in my own class. Here's an attempt:

from typing import Optional, TypedDict
import openai

class FileStatus(TypedDict):
    filename: str
    sha256: str
    file_id: Optional[str]
    batch_id: Optional[str]
    batch_status: Optional[openai.types.Batch.status]
    #                                         ~~~~~~
    # Variable not allowed in type expression Pylance(reportInvalidTypeForm)

What should I use as the type hint for batch_status? I'd prefer to avoid copy/pasting the Literal[...] expression from the OpenAI API if possible.

5
  • Is this along the lines of what you're asking for? stackoverflow.com/q/52838204/25441514 Commented Sep 16, 2024 at 21:09
  • @Anerdw I don't think that will produce a valid type annotation either. Commented Sep 16, 2024 at 21:58
  • 4
    unfortunately, if you want this to be useful for static type checkers (mypy and pyright) then you are probably just going to have to copy it. Commented Sep 16, 2024 at 21:59
  • 1
    A Literal isn't really a good way to define an enumerated type in the first place. Commented Sep 17, 2024 at 14:56
  • @chepner That's coming from the OpenAI library, it's not in my control. And what's the alternative for describing JSON? Commented Sep 18, 2024 at 18:03

1 Answer 1

0
from typing import Literal, Optional, TypedDict, get_type_hints


class Batch:
    id: str
    status: Literal[
        "validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"
    ]


type_hints = get_type_hints(Batch)
status_type = type_hints['status']


class FileStatus(TypedDict):
    filename: str
    sha256: str
    file_id: Optional[str]
    batch_id: Optional[str]
    batch_status: Optional[status_type] 

You can use get_type_hints from typing to get type of attributes from class.

Sign up to request clarification or add additional context in comments.

2 Comments

This is considered invalid by static type checkers, though.
For vscode / pyright, this seems to provide autocomplete in some contexts but not others github.com/danvk/gpt-batch-manager/issues/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.