Python 打字有什么东西相当于 TypeScript 的 `keyof` 来生成 Literal

bra*_*ipt 4 python types type-hinting typescript

在 TypeScript 中,我们能够根据对象的键创建“文字”类型:

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"
Run Code Online (Sandbox Code Playgroud)

Python 中是否有等效项(3.10+ 可以)用于基于字典创建类型提示?例如,

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
Run Code Online (Sandbox Code Playgroud)

che*_*ner 6

那没有。您需要Literal静态定义类型:

TastyFoodsKeys = Literal["pizza", "burger"]
Run Code Online (Sandbox Code Playgroud)

但是,您可以使用TastyFoodsKeys.__args__然后定义您的dict.

tasty_foods = dict(zip(TastyFoodsKeys.__args__, ['', '']))
Run Code Online (Sandbox Code Playgroud)

__args__属性未记录,因此使用风险需您自担。

正如评论中指出的,您可以使用typing.get_args(已记录)而不是__args__直接访问:

tasty_foods = dict(zip(typing.get_args(TastyFoodsKeys), ['', '']))
Run Code Online (Sandbox Code Playgroud)

dict但是,您可能根本不想使用 a 。也许您真正想要的是枚举类型。

from enum import StrEnum


class TastyFood(StrEnum):
    PIZZA = ''
    BURGER = ''
    # etc
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,无需使用内部未记录的“__args__”属性。您可以使用 [`typing.get_args`](https://docs.python.org/3/library/typing.html#typing.get_args) 来实现此目的。 (2认同)
  • */在“忘记`typing.get_args`”罐子里再放一块五分钱。* 夏威夷假期,我来了! (2认同)