Inspection for Optional types

Answered

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
my_string.startswith('test')

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

A simple check like this would solve the problem:

my_string: Optional[str] = None
if my_string:
my_string.startswith('test')

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

Hi,

Could you please report it to https://youtrack.jetbrains.com/issues/PY? If possible, please also attach a file with sample code to reproduce.

0

Please sign in to leave a comment.