在Dict []中为类型提示指示多个值 [英] Indicating multiple value in a Dict[] for type hints

查看:65
本文介绍了在Dict []中为类型提示指示多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何表示 Dict 的类型,它有两个采用两种不同类型值的键?例如:

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

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


推荐答案

您要查询的功能称为异构字典 ,您需要在其中为特定键定义特定类型的值。在带有字符串键的异构字典的类型中尚未实施,并且仍处于开放状态。当前的想法是使用所谓的 TypedDict ,该语法将允许使用以下语法:

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

请注意 mypy 项目已通过 mypy扩展名(标记为实验性)提供此类型- TypedDict

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






至少,我们可以要求值是 List 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.

这篇关于在Dict []中为类型提示指示多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆