Correct way to write type hints for keys and items

2020-02-13 08:25发布

问题:

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]