Inspection for Optional types


Type hinting in Python includes the Optional type. It is used whenever a variable can have a valid type or 'None'. Functions might take a parameter that optionally can be None or might return None as a result in some cases. Optional can be used to indicate that. Because Optional variables can be None it is necessary to check for that prior to performing any actions on it. Otherwise we get an error on runtime like in the example below.

my_string: Optional[str] = None

AttributeError: 'NoneType' object has no attribute 'startswith'

A simple check like this would solve the problem:

my_string: Optional[str] = None
if my_string:

We already have inspections for when types do not match. It would be nice to have an inspection that checks if Optionals are guarded/checked correctly.


1 comment


Could you please report it to If possible, please also attach a file with sample code to reproduce.


Please sign in to leave a comment.