Indicating multiple value in a Dict[] for type hints

前端 未结 1 1478
感情败类
感情败类 2021-02-04 11:29

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\': {})
相关标签:
1条回答
  • 2021-02-04 12:10

    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.

    0 讨论(0)
提交回复
热议问题