[Python] Python typing equivalent of TypeScript's keyof

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    In TypeScript, we have the ability to create a "literal" type based on the keys of an object:

    const tastyFoods = {
    pizza: '',
    burger: '',
    iceCream: '',
    fries: '',
    taco: '',
    sushi: '',
    spaghetti: '',
    donut: '',
    cookie: '',
    chicken: '',
    } as const;

    type TastyFoodsKeys = keyof typeof tastyFoods;
    // gives us:
    // type TastyFoodsKeys = "pizza" | "burger" | "iceCream" | "fries" | "taco" | "sushi" | "spaghetti" | "donut" | "cookie" | "chicken"


    Is there an equivalent in Python (3.10+ is fine) for creating type hints based on a dict? E.g.,

    from typing import Literal

    tasty_foods = {
    "pizza": '',
    "burger": '',
    "iceCream": '',
    "fries": '',
    "taco": '',
    "sushi": '',
    "spaghetti": '',
    "donut": '',
    "cookie": '',
    "chicken": '',
    }

    TastyFoodsKeys = Literal[list(tasty_foods.keys())]
    # except that doesn't work, obviously

    Continue reading...

Compartilhe esta Página