当键具有无效名称时键入Ddict

2024-05-21 02:19:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如

from typing import TypedDict

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

不是有效的Python代码,导致错误:

SyntaxError: illegal target for annotation

保留关键字也存在同样的问题:

class RandomAlphabet(TypedDict):
    return: str

抛出:

SyntaxError: invalid syntax

Tags: 代码fromimporttypingtargetfor字典错误
1条回答
网友
1楼 · 发布于 2024-05-21 02:19:18

根据PEP 589,您可以使用alternative syntax创建TypedDict,如下所示:

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

因此,在你的情况下,你可以写:

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.

相关问题 更多 >