简体   繁体   English

为键和项目编写类型提示的正确方法

[英]Correct way to write type hints for keys and items

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.我有一些 Python 代码(为 Python 3.5、3.6 和 3.7 运行)并使用 mypy 添加了一些用于静态类型检查的类型提示。

Please take a look at the following snippet:请看下面的片段:

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]

What are the correct type hint statements for def keys(cls) and def items(cls) ? def keys(cls)def items(cls)的正确类型提示语句是什么?

You can use typing module您可以使用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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM