【问题标题】:Check if the type of a variable is dict[str, Any] in Python在 Python 中检查变量的类型是否为 dict[str, Any]
【发布时间】:2021-11-02 22:38:25
【问题描述】:

我想检查一个变量的类型是否为:dict[str, Any]。 (在python中)

我尝试过的(不成功)是这样的:

myvar = {
 'att1' : 'some value',
 'att2' : 1
}


if not isinstance(myvar, dict[str, Any]):
  raise Exception('Input has the wrong type')

我收到以下错误消息:

TypeError: isinstance() 参数 2 不能是参数化泛型

我应该怎么做?

谢谢!

【问题讨论】:

  • 不要使用input 作为变量名。这是一种不好的做法。它是一个内置函数
  • mypy 这样的类型检查器可以为您检查。但不是在运行时。
  • 在我的实际代码中,我没有使用输入,我认为这样会使问题更容易理解,我改变了它

标签: python types typeerror


【解决方案1】:

试试下面的 - 确保你有一个 dict 并且 dict 的键是字符串。

data1 = {
    'att1': 'some value',
    'att2': 1
}

data2 = {
    'att1': 'some value',
    13: 1
}


def check_if_dict_with_str_keys(data):
    return isinstance(data, dict) and all(isinstance(x, str) for x in data.keys())


print(check_if_dict_with_str_keys(data1))
print(check_if_dict_with_str_keys(data2))

输出

True
False

【讨论】:

  • 哇!谢谢!
  • 如果你想在运行之前检查代码,请查看mypy
  • @balderman — 您可以删除对data.keys() 的调用,只需使用return isinstance(data, dict) and all(isinstance(x, str) for x in data)iter(data) 无论如何都会在字典的键上返回一个迭代器,并且比在 data.keys() 返回的 KeysView 代理上迭代更快。
  • 感谢 Alex 的提示。
【解决方案2】:

isinstance 不像类型提示那样工作。

正确的代码是:

if isinstance(input, dict):

但这并没有达到我认为你想要的效果:检查字典中的所有键是否都是 str 并且所有值都是 Any。基本上,您希望所有键都是 str,因此实现此目的的代码如下:

if all(map(lambda k: isinstance(k, str), input.keys())):

或类似的。

【讨论】:

    【解决方案3】:

    不支持您在此处尝试执行的操作:

    if not isinstance(input, dict[str, Any]):
    

    docs中提到的:

    内置函数 isinstance()issubclass() 不接受 GenericAlias 类型作为其第二个参数:

    >>> isinstance([1, 2], list[str])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: isinstance() argument 2 cannot be a parameterized generic
    

    相反,您只能执行以下操作:

    if not isinstance(input, dict):
    

    如果您想检查 dict 容器的元素的类型,您可以做的是遍历其项目,然后检查它们的类型(如其他答案中所做的那样)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多