Skip to content

Instantly share code, notes, and snippets.

@woile
Created August 2, 2022 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woile/6686e53daa7863557c45c4c1b783af6e to your computer and use it in GitHub Desktop.
Save woile/6686e53daa7863557c45c4c1b783af6e to your computer and use it in GitHub Desktop.
from typing import Literal, TypedDict
from enum import Enum
class Conn(str, Enum):
TCP = "TCP"
UDP = "UDP"
class TcpSettings(TypedDict):
conn: Literal[Conn.TCP]
foo: bool
t = TcpSettings(conn="TCP", foo=True)
# Incompatible types (expression has type "Literal['TCP']", TypedDict item "conn" has type "Literal[Conn.TCP]")mypy(error)
@woile
Copy link
Author

woile commented Aug 2, 2022

Possible solutions.

Use the enum for declaration

t = TcpSettings(conn= Conn.TCP, foo=True)

Use a str literal in the class

class TcpSettings(TypedDict):
    conn: Literal["TCP"]
    foo: bool

But is there a way to have both? An enum + letting users who use TcpSettings to avoid the enum by providing a str literal?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment