键名无效时的 TypedDict
TypedDict when keys have invalid names
如果我在字典中有一个带有无效标识符的键,例如 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
根据PEP 589 you can use 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.
这相当混乱,但如果您需要继承,它会起作用。
class RandomAlphabet(
TypedDict(
"RandomAlphabet",
{"A(2)": str, "return": str},
),
SomeInheritedTypedDict,
):
pass
您也可以将 pass
替换为其他不使用无效标识符或保留关键字(如果有的话)的普通属性。
如果我在字典中有一个带有无效标识符的键,例如 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
根据PEP 589 you can use 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.
这相当混乱,但如果您需要继承,它会起作用。
class RandomAlphabet(
TypedDict(
"RandomAlphabet",
{"A(2)": str, "return": str},
),
SomeInheritedTypedDict,
):
pass
您也可以将 pass
替换为其他不使用无效标识符或保留关键字(如果有的话)的普通属性。