我想知道如何使这个getter更安全:
VALUES = {
'1': 'One',
'2': 'Two',
'3': 'Three'
}
def get(key : str) -> str:
return VALUES[key]
我希望使用keyof VALUES
和type(VALUES[key])
类型,而不是str
类型
get('4')
应该抛出无效类型警告,因为该键不存在。我不确定这在Python中是否可行,因为我正生活在一个TypeScript仙境中:-)
TypeScript的正确外观如下所示:
get<K extends keyof VALUES>(key : K): typeof K
{
return VALUES[key];
}
正如评论中所建议的那样,
enum
模块在这里提供了一个很好的解决方案。通过将str
与enum.Enum
混合,我们可以创建一个与str
完全向后兼容的Enum
(即,可以在任何需要str
类型的地方使用)如果将此定义输入交互式控制台,我们将看到此类具有以下行为:
如您所见,我们定义了一种新类型:
str
完全向后兼容-它可以自由地与str
对象进行比较,并且str
方法可以在其成员上使用typing.Literal
的替代方法。如果我有这样一个函数:然后我可以这样注释它:
或者类似这样(在这种情况下,您必须传入
Values
枚举的成员,而不是普通字符串,否则类型检查器将引发错误):还有一个更详细的指南,介绍python
Enum
shere的复杂性一般来说,您不能这样做。但是,在这种特殊情况下,您可以使用^{} 实现您想要的:
相关问题 更多 >
编程相关推荐