Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypedDict when keys have invalid names

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
like image 370
johng Avatar asked Jan 31 '20 11:01

johng


People also ask

Do typed dicts with some keys missing need support for get?

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?

What is a typeddict type?

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).

How to specify required and optional keys in typing-SIG?

@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.

How to use the defaultdict type in Python?

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.


Video Answer


1 Answers

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.

like image 62
Georgy Avatar answered Sep 20 '22 11:09

Georgy