Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indicating multiple value in a Dict[] for type hints

How do I express the type of a Dict which has two keys that take two different types of values? For example:

a = {'1': [], '2': {})

The following is just to give you an idea of what I am looking for.

Dict[(str, List), (str, Set)]

like image 365
Nijan Avatar asked Jan 02 '18 01:01

Nijan


People also ask

How to add type hints to a dictionary?

Special construct to add type hints to a dictionary. At runtime it is a plain dict. TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers.

What is typed Dict in C++?

TypedDict (dict) ¶ Special construct to add type hints to a dictionary. At runtime it is a plain dict. TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type ...

How to set type hints for multiple types in Python?

To set type hints for multiple types, you can use Union from the typing module. Second, use the Union to create a union type that includes int and float: Starting from Python 3.10, you can use the X | Y syntax to create a union type, for example: Python allows you to assign an alias to a type and use the alias for type hintings. For example:

How do you indicate that a value is dynamically typed?

Use Any to indicate that a value is dynamically typed. Initially PEP 484 defined Python static type system as using nominal subtyping. This means that a class A is allowed where a class B is expected if and only if A is a subclass of B.


1 Answers

The feature you are asking about is called "Heterogeneous dictionaries" where you need to define specific types of values for the specific keys. The issue is being discussed at Type for heterogeneous dictionaries with string keys and is not yet implemented and is still open. The current idea is to use so-called TypedDict which would allow a syntax like:

class HeterogeneousDictionary(TypedDict):
    x: List
    y: Set

Note that mypy project has this type already available through the "mypy extensions" (marked as experimental) - TypedDict:

from mypy_extensions import TypedDict

HeterogeneousDictionary = TypedDict('HeterogeneousDictionary', {'1': List, '2': Set})

At the very least though, we can ask for values to be either List or Set using Union:

from typing import Dict, List, Set, Union

def f(a: Dict[str, Union[List, Set]]):
    pass

This is, of course, not ideal as we lose a lot of information about what keys need to have values of which types.

like image 138
alecxe Avatar answered Sep 19 '22 02:09

alecxe