为键和项目编写类型提示的正确方法 [英] Correct way to write type hints for keys and items

查看:59
本文介绍了为键和项目编写类型提示的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 Python 代码(针对 Python 3.5、3.6 和 3.7 运行),并为使用 mypy 的静态类型检查添加了一些类型提示.

I have some Python code (running for Python 3.5, 3.6 and 3.7) and added some type hints for static type checks using mypy.

请看下面的片段:

class MyParams(Singleton, metaclass=MyParamsMeta):
    @classmethod
    def keys(cls):  # TODO -> type?
        return cls._params.keys()

    @classmethod
    def items(cls):  # TODO -> type?
        return cls._params.items()

    _params = _load_from_csv()  # returns Dict[str, MyParam]

def keys(cls)def items(cls) 的正确类型提示语句是什么?

What are the correct type hint statements for def keys(cls) and def items(cls)?

推荐答案

你可以使用typing模块

import typing

class MyParams(Singleton, metaclass=MyParamsMeta):
    @classmethod
    def keys(cls) -> typing.collections.KeysView:
        return cls._params.keys()

    @classmethod
    def items(cls) -> typing.collections.ItemsView:
        return cls._params.items()

    _params = _load_from_csv()  # returns Dict[str, MyParam]

这篇关于为键和项目编写类型提示的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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