Check if the type of a variable is dict[str, Any] in Python

Viewed 1008

I want to check if the type of a variable is: dict[str, Any]. (in python)

What I have tried (unsuccessfully) is this:

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


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

I get the following error message:

TypeError: isinstance() argument 2 cannot be a parameterized generic

How should I do this?

Thank you!

3 Answers

Try the below - make sure you have a dict and the keys of the dict are strings.

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))

output

True
False

isinstance doesn't work like type hinting does.

The correct code for that is:

if isinstance(input, dict):

But that doesn't do what I think you want: check if all keys in the dict are str and all values are Any. Basically, you want all keys to be str, so the code to achieve that would be something like:

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

or some such.

What you are trying to do here is not supported:

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

As mentioned in the 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

Instead, you can only perform this:

if not isinstance(input, dict):

If you want to check the type of the elements of the dict container, what you can do is iterate over its items and then check their types (as done in the other answers).

Related