Search code examples
pythonpython-typingpydantic

Unable to use starred expression with Literal


I am working on a project and am trying to unpack a list so that I can make it a Literal for Pydantic library. But the code is throwing this error, Python version 3.10 does not support starred expressions in subscriptions.

Here is the code causing the error,

from pydantic import BaseModel
from typing import Literal

members = ["Member1", "Member2"]
options = ["FINISH"] + members

class routeResponse(BaseModel):
    next: Literal[*options] # <- this line is throwing error

The code is working just fine if I remove the Literal i.e., [*options] is working perfectly fine. So, the problem in using * and Literal together. Does anyone know what might be causing the error?

I am currently using python version 3.10.9.


Solution

  • Okays, so after a few more tries and checking different options from here and there I got the correct answer.

    Thanks to @kuza for mentioning that Literal accepts a tuple of types or literals here.

    After reading this response, I tried Literal[(*options,)] and now it is working as expected. Here is the full code just in case required.

    from pydantic import BaseModel
    from typing import Literal
    
    members = ["Member1", "Member2"]
    options = ["FINISH"] + members
    
    class routeResponse(BaseModel):
        next: Literal[(*options,)]