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?
E.g
from typing import TypedDict
class RandomAlphabet(TypedDict):
A(2): str
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
throws:
SyntaxError: invalid syntax
We don't have a complete story for typed dicts when some keys may be missing. Support for get ( #2612) is necessary, but it may not be sufficient. For example, consider code like this: Should it be possible to make this type check without a cast?
A TypedDict type represents dictionary objects with a specific set of string keys, and with specific value types for each valid key. Each string key can be either required (it must be present) or non-required (it doesn’t need to exist).
@ppo Right now the way to specify some keys as required and some as optional is to have a total=False TypedDict inherit from a total=True TypedDict: On the typing-sig mailing list there is an active discussion right now about new syntax to mark individual keys as required keys and others as optional keys.
A typical use of the Python defaultdict type is to set .default_factory to list and then build a dictionary that maps keys to lists of values. With this defaultdict, if you try to get access to any missing key, then the dictionary runs the following steps: Here, you create a Python defaultdict called dd and pass list to .default_factory.
According to PEP 589 you can use alternative syntax to create a TypedDict
as follows:
Movie = TypedDict('Movie', {'name': str, 'year': int})
So, in your case, you could write:
from typing import TypedDict
RandomAlphabet = TypedDict('RandomAlphabet', {'A(2)': str})
or for the second example:
RandomAlphabet = TypedDict('RandomAlphabet', {'return': str})
PEP 589 warns, though:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With