mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-27 08:29:59 +03:00
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()
This commit is contained in:
parent
b95b6f0cbb
commit
b9a57af6d4
|
@ -1,3 +1,4 @@
|
||||||
|
import contextlib
|
||||||
import sys
|
import sys
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from urllib import parse
|
from urllib import parse
|
||||||
|
@ -170,7 +171,7 @@ class RelatedField(Field):
|
||||||
def get_attribute(self, instance):
|
def get_attribute(self, instance):
|
||||||
if self.use_pk_only_optimization() and self.source_attrs:
|
if self.use_pk_only_optimization() and self.source_attrs:
|
||||||
# Optimized case, return a mock object only containing the pk attribute.
|
# 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])
|
attribute_instance = get_attribute(instance, self.source_attrs[:-1])
|
||||||
value = attribute_instance.serializable_value(self.source_attrs[-1])
|
value = attribute_instance.serializable_value(self.source_attrs[-1])
|
||||||
if is_simple_callable(value):
|
if is_simple_callable(value):
|
||||||
|
@ -183,9 +184,6 @@ class RelatedField(Field):
|
||||||
value = getattr(value, 'pk', value)
|
value = getattr(value, 'pk', value)
|
||||||
|
|
||||||
return PKOnlyObject(pk=value)
|
return PKOnlyObject(pk=value)
|
||||||
except AttributeError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Standard case, return the object instance.
|
# Standard case, return the object instance.
|
||||||
return super().get_attribute(instance)
|
return super().get_attribute(instance)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user