Skip to content

Commit c10f226

Browse files
authored
Refactor: Replace try/except with contextlib.suppress() (#8676)
1 parent 99cf2c4 commit c10f226

File tree

8 files changed

+31
-54
lines changed

8 files changed

+31
-54
lines changed

rest_framework/fields.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import copy
23
import datetime
34
import decimal
@@ -690,15 +691,13 @@ class BooleanField(Field):
690691
NULL_VALUES = {'null', 'Null', 'NULL', '', None}
691692

692693
def to_internal_value(self, data):
693-
try:
694+
with contextlib.suppress(TypeError):
694695
if data in self.TRUE_VALUES:
695696
return True
696697
elif data in self.FALSE_VALUES:
697698
return False
698699
elif data in self.NULL_VALUES and self.allow_null:
699700
return None
700-
except TypeError: # Input is an unhashable type
701-
pass
702701
self.fail('invalid', input=data)
703702

704703
def to_representation(self, value):
@@ -1158,19 +1157,14 @@ def to_internal_value(self, value):
11581157
return self.enforce_timezone(value)
11591158

11601159
for input_format in input_formats:
1161-
if input_format.lower() == ISO_8601:
1162-
try:
1160+
with contextlib.suppress(ValueError, TypeError):
1161+
if input_format.lower() == ISO_8601:
11631162
parsed = parse_datetime(value)
11641163
if parsed is not None:
11651164
return self.enforce_timezone(parsed)
1166-
except (ValueError, TypeError):
1167-
pass
1168-
else:
1169-
try:
1170-
parsed = self.datetime_parser(value, input_format)
1171-
return self.enforce_timezone(parsed)
1172-
except (ValueError, TypeError):
1173-
pass
1165+
1166+
parsed = self.datetime_parser(value, input_format)
1167+
return self.enforce_timezone(parsed)
11741168

11751169
humanized_format = humanize_datetime.datetime_formats(input_formats)
11761170
self.fail('invalid', format=humanized_format)

rest_framework/pagination.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
Pagination serializers determine the structure of the output that should
33
be used for paginated responses.
44
"""
5+
6+
import contextlib
57
from base64 import b64decode, b64encode
68
from collections import OrderedDict, namedtuple
79
from urllib import parse
@@ -257,15 +259,12 @@ def get_paginated_response_schema(self, schema):
257259

258260
def get_page_size(self, request):
259261
if self.page_size_query_param:
260-
try:
262+
with contextlib.suppress(KeyError, ValueError):
261263
return _positive_int(
262264
request.query_params[self.page_size_query_param],
263265
strict=True,
264266
cutoff=self.max_page_size
265267
)
266-
except (KeyError, ValueError):
267-
pass
268-
269268
return self.page_size
270269

271270
def get_next_link(self):
@@ -430,15 +429,12 @@ def get_paginated_response_schema(self, schema):
430429

431430
def get_limit(self, request):
432431
if self.limit_query_param:
433-
try:
432+
with contextlib.suppress(KeyError, ValueError):
434433
return _positive_int(
435434
request.query_params[self.limit_query_param],
436435
strict=True,
437436
cutoff=self.max_limit
438437
)
439-
except (KeyError, ValueError):
440-
pass
441-
442438
return self.default_limit
443439

444440
def get_offset(self, request):
@@ -680,15 +676,12 @@ def paginate_queryset(self, queryset, request, view=None):
680676

681677
def get_page_size(self, request):
682678
if self.page_size_query_param:
683-
try:
679+
with contextlib.suppress(KeyError, ValueError):
684680
return _positive_int(
685681
request.query_params[self.page_size_query_param],
686682
strict=True,
687683
cutoff=self.max_page_size
688684
)
689-
except (KeyError, ValueError):
690-
pass
691-
692685
return self.page_size
693686

694687
def get_next_link(self):

rest_framework/parsers.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
They give us a generic way of being able to handle various media types
55
on the request, such as form content or json encoded data.
66
"""
7+
78
import codecs
9+
import contextlib
810

911
from django.conf import settings
1012
from django.core.files.uploadhandler import StopFutureHandlers
@@ -193,17 +195,12 @@ def get_filename(self, stream, media_type, parser_context):
193195
Detects the uploaded file name. First searches a 'filename' url kwarg.
194196
Then tries to parse Content-Disposition header.
195197
"""
196-
try:
198+
with contextlib.suppress(KeyError):
197199
return parser_context['kwargs']['filename']
198-
except KeyError:
199-
pass
200200

201-
try:
201+
with contextlib.suppress(AttributeError, KeyError, ValueError):
202202
meta = parser_context['request'].META
203203
disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION'])
204204
if 'filename*' in params:
205205
return params['filename*']
206-
else:
207-
return params['filename']
208-
except (AttributeError, KeyError, ValueError):
209-
pass
206+
return params['filename']

rest_framework/relations.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import sys
23
from collections import OrderedDict
34
from urllib import parse
@@ -170,7 +171,7 @@ def use_pk_only_optimization(self):
170171
def get_attribute(self, instance):
171172
if self.use_pk_only_optimization() and self.source_attrs:
172173
# Optimized case, return a mock object only containing the pk attribute.
173-
try:
174+
with contextlib.suppress(AttributeError):
174175
attribute_instance = get_attribute(instance, self.source_attrs[:-1])
175176
value = attribute_instance.serializable_value(self.source_attrs[-1])
176177
if is_simple_callable(value):
@@ -183,9 +184,6 @@ def get_attribute(self, instance):
183184
value = getattr(value, 'pk', value)
184185

185186
return PKOnlyObject(pk=value)
186-
except AttributeError:
187-
pass
188-
189187
# Standard case, return the object instance.
190188
return super().get_attribute(instance)
191189

rest_framework/renderers.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
77
REST framework also provides an HTML renderer that renders the browsable API.
88
"""
9+
910
import base64
11+
import contextlib
1012
from collections import OrderedDict
1113
from urllib import parse
1214

@@ -72,11 +74,8 @@ def get_indent(self, accepted_media_type, renderer_context):
7274
# then pretty print the result.
7375
# Note that we coerce `indent=0` into `indent=None`.
7476
base_media_type, params = parse_header_parameters(accepted_media_type)
75-
try:
77+
with contextlib.suppress(KeyError, ValueError, TypeError):
7678
return zero_as_none(max(min(int(params['indent']), 8), 0))
77-
except (KeyError, ValueError, TypeError):
78-
pass
79-
8079
# If 'indent' is provided in the context, then pretty print the result.
8180
# E.g. If we're being called by the BrowsableAPIRenderer.
8281
return renderer_context.get('indent', None)
@@ -488,11 +487,8 @@ def get_rendered_html_form(self, data, view, method, request):
488487
return
489488

490489
if existing_serializer is not None:
491-
try:
490+
with contextlib.suppress(TypeError):
492491
return self.render_form_for_serializer(existing_serializer)
493-
except TypeError:
494-
pass
495-
496492
if has_serializer:
497493
if method in ('PUT', 'PATCH'):
498494
serializer = view.get_serializer(instance=instance, **kwargs)

rest_framework/serializers.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
2. The process of marshalling between python primitives and request and
1111
response content is handled by parsers and renderers.
1212
"""
13+
14+
import contextlib
1315
import copy
1416
import inspect
1517
import traceback
@@ -1496,12 +1498,10 @@ def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
14961498
# they can't be nested attribute lookups.
14971499
continue
14981500

1499-
try:
1501+
with contextlib.suppress(FieldDoesNotExist):
15001502
field = model._meta.get_field(source)
15011503
if isinstance(field, DjangoModelField):
15021504
model_fields[source] = field
1503-
except FieldDoesNotExist:
1504-
pass
15051505

15061506
return model_fields
15071507

rest_framework/utils/encoders.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""
22
Helper classes for parsers.
33
"""
4+
5+
import contextlib
46
import datetime
57
import decimal
68
import json # noqa
@@ -58,10 +60,8 @@ def default(self, obj):
5860
)
5961
elif hasattr(obj, '__getitem__'):
6062
cls = (list if isinstance(obj, (list, tuple)) else dict)
61-
try:
63+
with contextlib.suppress(Exception):
6264
return cls(obj)
63-
except Exception:
64-
pass
6565
elif hasattr(obj, '__iter__'):
6666
return tuple(item for item in obj)
6767
return super().default(obj)

rest_framework/utils/serializer_helpers.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import sys
23
from collections import OrderedDict
34
from collections.abc import Mapping, MutableMapping
@@ -103,15 +104,13 @@ def as_form_field(self):
103104
# When HTML form input is used and the input is not valid
104105
# value will be a JSONString, rather than a JSON primitive.
105106
if not getattr(value, 'is_json_string', False):
106-
try:
107+
with contextlib.suppress(TypeError, ValueError):
107108
value = json.dumps(
108109
self.value,
109110
sort_keys=True,
110111
indent=4,
111112
separators=(',', ': '),
112113
)
113-
except (TypeError, ValueError):
114-
pass
115114
return self.__class__(self._field, value, self.errors, self._prefix)
116115

117116

0 commit comments

Comments
 (0)