检查Python中变量的类型是否为 dict[str, Any]

lio*_*nel 5 python types typeerror

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

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

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


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

我收到以下错误消息:

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

我该怎么做?

谢谢你!

bal*_*man 7

尝试以下操作 - 确保您有一个字典并且该字典的键是字符串。

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))
Run Code Online (Sandbox Code Playgroud)

输出

True
False
Run Code Online (Sandbox Code Playgroud)