Correct way to write type hints for keys and items

泄露秘密 提交于 2019-11-28 06:54:54

问题


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.

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


回答1:


You can use typing module

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]


来源:https://stackoverflow.com/questions/55509647/correct-way-to-write-type-hints-for-keys-and-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!