如何键入提示 getter 仅允许 dict 的键?

red*_*dia 5 python type-hinting keyof python-typing

我想知道如何使这个 getter 更加类型安全:

VALUES = {
   '1': 'One',
   '2': 'Two',
   '3': 'Three'
}


def get(key : str) -> str:
    return VALUES[key]
Run Code Online (Sandbox Code Playgroud)

str我希望有一个keyof VALUESand类型,而不是类型type(VALUES[key])

get('4')应该抛出无效类型警告,因为该键不存在。不确定这对于 Python 是否可行,因为我确实生活在 TypeScript 仙境中......:-)

TypeScript 正确的样子应该是这样的:

VALUES = {
   '1': 'One',
   '2': 'Two',
   '3': 'Three'
}


def get(key : str) -> str:
    return VALUES[key]
Run Code Online (Sandbox Code Playgroud)

jua*_*aga 6

一般情况下你不能这样做。但是,在这种特殊情况下,您可以使用以下方法来完成您想要的操作typing.Literal

import typing
def get(key: typing.Literal['1','2','3']) -> str:
    return VALUES[key]
Run Code Online (Sandbox Code Playgroud)

  • @enzo 当然,OP 知道我很确定 (2认同)