检查变量的类型是否为 dict[str, Any] in Python
Check if the type of a variable is dict[str, Any] in Python
我想检查一个变量的类型是不是: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() argument 2 cannot be a parameterized generic
我应该怎么做?
谢谢!
试试下面的方法 - 确保你有一个字典并且字典的键是字符串。
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
isinstance
不像类型提示那样工作。
正确的代码是:
if isinstance(input, dict):
但这并不符合我的想法:检查字典中的所有键是否都是 str 并且所有值都是 Any。基本上,您希望所有键都是 str,因此实现该目标的代码类似于:
if all(map(lambda k: isinstance(k, str), input.keys())):
或类似的。
不支持您在此处尝试执行的操作:
if not isinstance(input, dict[str, Any]):
如docs所述:
The builtin functions isinstance()
and issubclass()
do not accept GenericAlias
types for their second argument:
>>> 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
容器的元素类型,你可以做的是遍历它的项目,然后检查它们的类型(就像在其他答案中所做的那样)。
我想检查一个变量的类型是不是: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() argument 2 cannot be a parameterized generic
我应该怎么做?
谢谢!
试试下面的方法 - 确保你有一个字典并且字典的键是字符串。
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
isinstance
不像类型提示那样工作。
正确的代码是:
if isinstance(input, dict):
但这并不符合我的想法:检查字典中的所有键是否都是 str 并且所有值都是 Any。基本上,您希望所有键都是 str,因此实现该目标的代码类似于:
if all(map(lambda k: isinstance(k, str), input.keys())):
或类似的。
不支持您在此处尝试执行的操作:
if not isinstance(input, dict[str, Any]):
如docs所述:
The builtin functions
isinstance()
andissubclass()
do not acceptGenericAlias
types for their second argument:>>> 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
容器的元素类型,你可以做的是遍历它的项目,然后检查它们的类型(就像在其他答案中所做的那样)。