按键名称无效时的TypedDict [英] TypedDict when keys have invalid names

查看:140
本文介绍了按键名称无效时的TypedDict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的词典中的键的标识符无效,例如 A(2)。如何使用此字段创建 TypedDict

If I have a key in a dictionary with an invalid identifier, such as A(2). How can I create a TypedDict with this field?

例如

from typing import TypedDict

class RandomAlphabet(TypedDict):
    A(2): str

无效Python代码,导致错误:

is not valid Python code, resulting in the error:

SyntaxError: illegal target for annotation

相同的问题是保留关键字:

The same problem is with reserved keywords:

class RandomAlphabet(TypedDict):
    return: str

抛出:

SyntaxError: invalid syntax


推荐答案

根据 PEP 589 ,您可以使用替代语法来创建 TypedDict ,如下所示:

According to PEP 589 you can use alternative syntax to create a TypedDict as follows:


电影= TypedDict('电影',{'name':str,'year':int})

因此,在您的情况下,您可以输入:

So, in your case, you could write:

from typing import TypedDict

RandomAlphabet = TypedDict('RandomAlphabet', {'A(2)': str})

或第二个示例:

RandomAlphabet = TypedDict('RandomAlphabet', {'return': str})




PEP 589 警告:


但是,该语法不支持继承,因此没有
的方法单一类型的必填字段和非必填字段。
这样做的动机是使向后兼容的语法尽可能简单地保持
,同时覆盖最常见的用例。

This syntax doesn't support inheritance, however, and there is no way to have both required and non-required fields in a single type. The motivation for this is keeping the backwards compatible syntax as simple as possible while covering the most common use cases.

这篇关于按键名称无效时的TypedDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆