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

2024-02-22

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

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


def get(key : str) -> str:
    return VALUES[key]

而不是类型str我很想有一个keyof VALUES and type(VALUES[key]) types.

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

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

get<K extends keyof VALUES>(key : K): typeof K
{
    return VALUES[key];
}

You 一般来说不能这样做。但是,在这种特殊情况下,您可以使用以下命令来完成您想要的操作:typing.Literal https://www.python.org/dev/peps/pep-0586/:

import typing
def get(key: typing.Literal['1','2','3']) -> str:
    return VALUES[key]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何键入提示 getter 仅允许 dict 的键? 的相关文章

随机推荐