Mypy – how to fix incompatible type inside list comprehensions?

Question:

It’s a pyspark.

I’m looking for a way to fix an error from mypy about the wrong type for an element inside a list comprehension – data_frame[x].

The error:

List item 0 has incompatible type "List[Column]"; expected "str" 
[list-item]

It refers to this line of a code:

columns = list(set(columns + [*[data_frame[x] for x in LIST_COLUMNS if x not in columns]]))

LIST_COLUMNS = list of strings

columns = list of strings

I’m completely failing to find a way to fix it. Can anyone share some hints? What idea you’d have to solve it?

Asked By: QbS

||

Answers:

One possible solution to solve this error would be to convert the elements of the list comprehension to strings before adding them to the list. You could do this by using the map() function.

For example, you could change the code to this:

columns = list(set(columns + [*map(str, [data_frame[x] for x in LIST_COLUMNS if x not in columns])]))

This would convert all the elements of the list comprehension to strings before adding them to the list.Let me know if this help you.

Answered By: apan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.