Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将函数返回类型指定为dict';s键视图_Python_Pycharm_Python 3.5_Python 3.6_Typing - Fatal编程技术网

Python 将函数返回类型指定为dict';s键视图

Python 将函数返回类型指定为dict';s键视图,python,pycharm,python-3.5,python-3.6,typing,Python,Pycharm,Python 3.5,Python 3.6,Typing,在PyCharm中,我得到了以下Python 3代码: def get_dict_keys(d: dict) -> list: assert(isinstance(d, dict)) return d.keys() 检查代码时,我发现以下错误: Expected type 'list', got 'KeysView' instead 我想指定正确的返回代码以抑制此警告。Python的类型库支持指定Iterable类型: from typing import Iterab

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

def get_dict_keys(d: dict) -> list:
    assert(isinstance(d, dict))
    return d.keys()
检查代码时,我发现以下错误:

Expected type 'list', got 'KeysView' instead

我想指定正确的返回代码以抑制此警告。

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

from typing import Iterable

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

从这个问题上看,你不清楚你想朝哪个方向去纠正它。该方法是否应该返回一个列表,在这种情况下,错误的是代码而不是类型?如果代码是正确的,那么如果它返回一个特定的
KeysView
(而不是一个通用的
Iterable
)是否真的很重要?坦白地说,在的上下文中编写这种方法看起来很奇怪。@jornsharpe,我希望保持代码的原样,但修复警告。我同意您的观点,指定
键入.Iterable
键入要好。KeysView
可能重复的属性为什么您认为
键入.Iterable
键入.KeysView
好?KeyView更好,因为它在操作中有
\uuu包含
fo
(如果我错了请纠正我),所以它更接近dict键的许多用法。当然,在duck类型的上下文中,您根本不需要任何类型提示。