【问题标题】:Correct way to write type hints for keys and items为键和项目编写类型提示的正确方法
【发布时间】:2019-08-25 20:06:48
【问题描述】:

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

请看下面的sn-p:

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) 的正确类型提示语句是什么?

【问题讨论】:

  • 您查看过typing 文档吗?它提供例如KeysView.

标签: python python-3.5 type-hinting typing


【解决方案1】:

你可以使用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]

【讨论】:

  • typing.collections.KeysView 在我的设置中没有找到,但是 typing.KeyView 没问题(python 3.6.8)
  • @al.zatv python Python 3.6.8 (default, Aug 20 2019, 17:12:48) Type 'copyright', 'credits' or 'license' for more information IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import typing In [2]: typing.collections.KeysView Out[2]: collections.abc.KeysView In [3]:
猜你喜欢
  • 2016-12-05
  • 2012-02-19
  • 2020-05-14
  • 2021-11-18
  • 1970-01-01
  • 2020-10-24
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多