sourcery-ai / sourcery

Instant AI code reviews
https://sourcery.ai
MIT License
1.53k stars 66 forks source link

Incorrect "Remove unreachable except block" while using Django Rest Framework #266

Closed pzelnip closed 2 years ago

pzelnip commented 2 years ago

Issue description or question

With this snippet:

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

class MySerializer(serializers.Serializer):
    param = serializers.ListField()

s = MySerializer(data={})  # is not valid data
try:
    s.is_valid(raise_exception=True)
except ValueError as exc:
    print('value error')
except ValidationError as exc:
    print('validation error')

Sourcery incorrectly marks the 2nd except handler (for ValidationError) as unreachable:

Screen Shot 2022-08-10 at 11 19 54 AM

Yet when I run this program, it prints out "validation error" indicating that handler was reached. Furthermore after applying the refactor (removing the ValidationError handler) the program now errors with a ValidationError exception:

    240 
    241         if self._errors and raise_exception:
--> 242             raise ValidationError(self.errors)
    243 
    244         return not bool(self._errors)

ValidationError: {'param': [ErrorDetail(string='This field is required.', code='required')]}

rest_framework is the Django Rest Framework

Sourcery Version

VS Code extension v0.12.6

Code editor or IDE name and version

VS Code:

I ran the snippet in a Python 3.9 venv, and the version of DRF installed is 3.11.0.

OS name and version

OSX Monterey 12.4

brendanator commented 2 years ago

Thanks for reporting this @pzelnip, I can reproduce this and it will be fixed in the next release

Hellebore commented 2 years ago

Fixed in 0.12.7