-1

I have a function, it takes in a list and return a list, when I writes unit test for it, I found the function won't raise error if the input is dict or a str, is this acceptable in Python? I couldn't find related info, if this is not acceptable, how can I specify the input type to list only?

This is the function:

def list_id_in_list(string_list: list) -> list:

    id_list = []
    for id in map(pre_defined_id_list, string_list):
        if not id:
            id_list.append([])
        else:
            id_list.append([i[2] for i in id])


    return id_list

This function maps the pre-defined id list to the given string list, go through the string list and see if it has any id string, then return a list that only contain the identified id.

This function seems works fine with str and dict input type and returns blank list, how can I modify it and specify the input to list? Hope this makes sense, thanks.

1 Answer 1

2

Python's type annotations are just hints, they are not enforced.

This is partly to allow duck typing (e.g. you could pass in a tuple of strings, or a generator of strings, ...).

If you need enforcing, you could add

if not isinstance(string_list, list):
    raise TypeError("string_list must be a list")
if not all(isinstance(val, str) for val in string_list):
    raise TypeError("string_list members must all be strings")

or similar to the function.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, just wondering if 'forcing input type' is a good practice?
In generally it's not, in my opinion. You can use type checkers such as mypy to statically type-check your program though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.