'How to check list of strings parameter type from isinstance() method

I want to try to handle the parameter type passed to the function by using isinstance() function. Basically, i want to check that whether passed list to the function contains only string or not. So, I wrote function as

def fun(parameter: list[str]):
    #want to check parameter type here

After getting the list, I want to ensure that it contains only strings. So, is there any way to check this from isinstance() function? Otherwise i have to make custom check by looping through the list.



Solution 1:[1]

This is kind of an odd, roundabout way of doing it, but here's how you could get away without using a loop. I prefer @OneCricketeer's answer in general though.

import numpy as np


def fun(parameter: list[str]):
    assert list(np.array(parameter, dtype=str)) == parameter
   ...

Passing dtype=str will cause any non-string items in parameter to be converted to strings in the resulting array, which you can then convert back to a list and compare to the original. The two will be equal only if all items were strings already.

You could also use np.array_equal() instead of wrapping the array in list() and comparing with ==, which would be more efficient if your parameter list is very large.

Solution 2:[2]

You can use 2 methods:
Method 1: Using the built-in function of python3 i.e isinstance().\

example:

def fun(parameter: list[str]):
 return isinstance(parameter, (list, str))

This will return the True or False. It will check parameter is list or string or a list of strings.

Method 2: create the custom function to check the type.

example:

def fun(parameter:list[str]):
     if type(parameter) == list:
            for i in parameter:
                 if type(i) != str:
                       return False
            return True
     return False

The logic behind the above code is simple it will check whether the parameter is list or not if a list will send False. If it is list then it will check the contains of the list are true or not. If they are true it simply returns True.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Madhav