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.
Please sign in to leave a 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.
The issue has been created, but the link was missing here.
Btw. if you search for the exact title, it is not shown on the first page. At least it is shown as similar issue, if you create a new issue with the same title. From this I conclude, you should use the form to create new issues to search for existing issues ;-)
Added a Hoare's quote to PY-32887 and reposted it to the Pycharm blog. We should campaign for this feature! :D