From b9a57af6d4484403a45cda77a25177e640fcfa6b Mon Sep 17 00:00:00 2001 From: ahzam Date: Wed, 28 Sep 2022 01:07:14 +0500 Subject: [PATCH] replace try/except block with context manager If the desire is to simply suppress an error, rather than perform some sort of branching logic, the Python standard library has a paradigm for that: contextlib.suppress() --- rest_framework/relations.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index bdedd43b8..62da685fb 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,3 +1,4 @@ +import contextlib import sys from collections import OrderedDict from urllib import parse @@ -170,7 +171,7 @@ class RelatedField(Field): def get_attribute(self, instance): if self.use_pk_only_optimization() and self.source_attrs: # Optimized case, return a mock object only containing the pk attribute. - try: + with contextlib.suppress(AttributeError): attribute_instance = get_attribute(instance, self.source_attrs[:-1]) value = attribute_instance.serializable_value(self.source_attrs[-1]) if is_simple_callable(value): @@ -183,9 +184,6 @@ class RelatedField(Field): value = getattr(value, 'pk', value) return PKOnlyObject(pk=value) - except AttributeError: - pass - # Standard case, return the object instance. return super().get_attribute(instance)