Search code examples
pythonlisttypesparameters

Is there a way to set "array of strings" as a type for a parameter in a function?


I want to check right at the passing of the arguments to a function if the argument is an array of strings.

Like setting a type to the parameter of the function to "array of string". But I don't want to loop through the array looking for none-string elements.

Is there a type like this?


Solution

  • Will a lambda function work?

    def check_arr_str(li):
    
        #Filter out elements which are of type string
        res = list(filter(lambda x: isinstance(x,str), li))
    
        #If length of original and filtered list match, all elements are strings, otherwise not
        return (len(res) == len(li) and isinstance(li, list))
    
    

    The outputs will look like

    print(check_arr_str(['a','b']))
    #True
    print(check_arr_str(['a','b', 1]))
    #False
    print(check_arr_str(['a','b', {}, []]))
    #False
    print(check_arr_str('a'))
    #False
    

    If an exception is needed, we can change the function as follows.

    def check_arr_str(li):
    
        res = list(filter(lambda x: isinstance(x,str), li))
        if (len(res) == len(li) and isinstance(li, list)):
            raise TypeError('I am expecting list of strings')
    

    Another way we can do this is using any to check if we have any item in the list which is not a string, or the parameter is not a list (Thanks @Netwave for the suggestion)

    def check_arr_str(li):
    
        #Check if any instance of the list is not a string
        flag = any(not isinstance(i,str) for i in li)
    
        #If any instance of an item  in the list not being a list, or the input itself not being a list is found, throw exception
        if (flag or not isinstance(li, list)):
            raise TypeError('I am expecting list of strings')