【问题标题】:Specifying function return type to be dict's KeysView指定函数返回类型为dict的KeysView
【发布时间】:2017-11-12 21:40:42
【问题描述】:

在 PyCharm 中,我得到了以下 Python 3 代码:

def get_dict_keys(d: dict) -> list:
    assert(isinstance(d, dict))
    return d.keys()

检查代码时出现以下错误:

Expected type 'list', got 'KeysView' instead

我想指定正确的返回码以消除此警告。

【问题讨论】:

  • 从问题在哪个方向您想更正它并不清楚。 应该该方法返回一个列表,在这种情况下是代码错误而不是打字错误?如果代码正确,那么它是否专门返回KeysView(而不是一般的Iterable)真的很重要吗?坦率地说,在duck typing 的上下文中,这似乎是一种奇怪的写法。
  • @jonrsharpe,我想保持代码不变,但修复警告。我同意你的观点,指定 typing.Iterabletyping.KeysView 更好
  • 为什么你认为typing.Iterabletyping.KeysView好? KeysView 更好,因为它有 __contains__ fo in 操作(如果我错了,请纠正我),所以它更接近 dict 键的许多用法。当然,在鸭子类型的上下文中,您根本不需要任何类型提示。

标签: python pycharm python-3.5 python-3.6 typing


【解决方案1】:

Python 的类型库支持指定Iterable 类型:

from typing import Iterable

def get_dict_keys(d: dict) -> Iterable:
    assert(isinstance(d, dict))
    return d.keys()

【讨论】:

    猜你喜欢
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2020-09-10
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多