error: Item "None" of "Optional[str]" has no attribute "split" [union-attr] MyPy Error

80 views Asked by At
# If word count threshold is set, calculate the total word count
            if self.word_count_threshold:
                word_count += len(documents[doc_idx].content.split())

For this code snippet mypy gives an error. Is there an alternative to using .split() here so mypy does not give this error? Is there an PEP8 convention or type casting that has to be done to resolve this?

1

There are 1 answers

0
climate-coder On

mypy is not a very smart tool. I'm experiencing similar issues with the tool. I'm almost thinking I remove this from my CI pipeline. Nonetheless, this might help you: https://stackoverflow.com/a/75371117/16314572

Personally, though, and while it might beat the entire purpose of mypy, I tend to just ignore unnecessary errors that mypy throws. In my case, I know for a fact, the code is doing exactly what it's supposed to do and will not error so ignoring type checking for that line makes sense. If you want to do that, in the line that's throwing an error do this:

...code # type: ignore