如何在Python 3.6中使用具有不同值类型的Dict使用静态类型检查? [英] How to use static type checking using Dict with different value types in Python 3.6?

查看:213
本文介绍了如何在Python 3.6中使用具有不同值类型的Dict使用静态类型检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Python代码中使用静态类型,因此mypy可以帮助我解决一些隐藏的错误.使用单个变量非常简单

Trying to use static types in Python code, so mypy can help me with some hidden errors. It's quite simple to use with single variables

real_hour: int = lower_hour + hour_iterator

更难将其与列表和字典一起使用,需要导入其他typing库:

Harder to use it with lists and dictionaries, need to import additional typing library:

from typing import Dict, List
hour_dict: Dict[str, str] = {"test_key": "test_value"}

但是主要的问题-如何将其与具有不同值类型的Dicts结合使用,例如:

But the main problem - how to use it with Dicts with different value types, like:

hour_dict = {"test_key": "test_value", "test_keywords": ["test_1","test_2"]}

如果我不对此类词典使用静态输入-mypy向我显示错误,例如:

If I don't use static typing for such dictionaries - mypy shows me errors, like:

len(hour_dict['test_keywords'])
- Argument 1 to "len" has incompatible type

所以,我的问题是:如何向此类词典添加静态类型? :)

So, my question: how to add static types to such dictionaries? :)

推荐答案

您需要某种类型的Union类型.

You need a Union type, of some sort.

from typing import Dict, List, Union

# simple str values
hour_dict: Dict[str, str] = {"test_key": "test_value"}

# more complex values
hour_dict1: Dict[str, Union[str, List[str]]] = {
    "test_key": "test_value", 
    "test_keywords": ["test_1","test_2"]
}

通常,当您需要此或那个"时,您需要一个Union.在这种情况下,您的选项是strList[str].

In general, when you need an "either this or that," you need a Union. In this case, your options are str and List[str].

有几种方法可以解决这个问题.例如,您可能想定义类型名称以简化内联类型.

There are several ways to play this out. You might, for example, want to define type names to simplify inline types.

OneOrManyStrings = Union[str, List[str]]

hour_dict2: Dict[str, OneOrManyStrings] = {
    "test_key": "test_value", 
    "test_keywords": ["test_1","test_2"]
}

我可能还建议您出于简单性,并行性和规则性的考虑,即使只有一项,也要使所有dict值纯为List[str].这样,您就可以始终取值的len(),而无需事先进行类型检查或保护条件.但是,这些要点是细微的调整.

I might also advise for simplicity, parallelism, and regularity to make all your dict values pure List[str] even if there's only one item. This would allow you to always take the len() of a value, without prior type checking or guard conditions. But those points are nits and tweaks.

这篇关于如何在Python 3.6中使用具有不同值类型的Dict使用静态类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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