1 year ago

#76827

test-img

balbok

Python 3 type Dict with required and arbitrary keys

I'm trying to type a function that returns a dictionary with one required key, and some additional ones.

I've run into TypedDict, but it is too strict for my purpose. At the same time Dict is too lenient.

To give some examples with what I have in mind:

class Schema(PartiallyTypedDict):
    name: str
    year: int

a: Schema = {"name": "a", "year": 1}  # OK
b: Schema = {"name": "a", "year": 1, rating: 5}  # OK, "rating" key can be added
c: Schema = {"year": 1, rating: 5}  # NOT OK, "name" is missing

It would be great if there was also a way of forcing values of all of the optional/arbitrary key to be of a specific type. For example int in example above due to "rating" being one.

Does there exist such a type, or is there a way of creating such a type in python typing framework?

python

python-typing

0 Answers

Your Answer

Accepted video resources