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)
那没有。您需要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)
| 归档时间: |
|
| 查看次数: |
906 次 |
| 最近记录: |