chore(ruff): Enable RET rules and add explicit fallbacks

Adopt Ruff `RET` to improve return-flow consistency across the codebase.
Simplify control flow by removing redundant `else` blocks after
`return`, and add explicit `return None` (or equivalent) fallbacks
where appropriate to preserve existing behavior.

Fixes #21411
This commit is contained in:
Martin Hauser
2026-02-18 22:22:47 +01:00
committed by Jeremy Stretch
parent b22e490847
commit ef52ac4203
77 changed files with 249 additions and 249 deletions

View File

@@ -133,15 +133,14 @@ class RestrictedGenericForeignKey(GenericForeignKey):
ct_id = getattr(obj, ct_attname)
if ct_id is None:
return None
else:
if model := self.get_content_type(
id=ct_id, using=obj._state.db
).model_class():
return (
model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),
model,
)
return None
if model := self.get_content_type(
id=ct_id, using=obj._state.db
).model_class():
return (
model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),
model,
)
return None
return (
ret_val,

View File

@@ -50,6 +50,6 @@ class ExpandableIPAddressField(forms.CharField):
# Hackish address family detection but it's all we have to work with
if '.' in value and re.search(IP4_EXPANSION_PATTERN, value):
return list(expand_ipaddress_pattern(value, 4))
elif ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
if ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
return list(expand_ipaddress_pattern(value, 6))
return [value]

View File

@@ -139,7 +139,7 @@ def get_field_value(form, field_name):
if form.is_bound and field_name in form.data:
if (value := form.data[field_name]) is None:
return
return None
if hasattr(field, 'valid_value') and field.valid_value(value):
return value

View File

@@ -37,8 +37,7 @@ def foreground_color(bg_color, dark='000000', light='ffffff'):
r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)]
if r * 0.299 + g * 0.587 + b * 0.114 > THRESHOLD:
return dark
else:
return light
return light
def highlight(value, highlight, trim_pre=None, trim_post=None, trim_placeholder='...'):

View File

@@ -25,7 +25,7 @@ def process_request_as_job(view, request, name=None):
# Check that the request that is not already being processed as a background job (would be a loop)
if is_background_request(request):
return
return None
# Create a serializable copy of the original request
request_copy = copy_safe_request(request)

View File

@@ -54,3 +54,4 @@ def resolve_proxies(url=None, protocol=None, context=None):
router = import_string(item) if type(item) is str else item
if proxies := router().route(url=url, protocol=protocol, context=context):
return proxies
return None

View File

@@ -67,7 +67,7 @@ def reapply_model_ordering(queryset: QuerySet) -> QuerySet:
# MPTT-based models are exempt from this; use caution when annotating querysets of these models
if any(isinstance(manager, TreeManager) for manager in queryset.model._meta.local_managers):
return queryset
elif queryset.ordered:
if queryset.ordered:
return queryset
ordering = queryset.model._meta.ordering

View File

@@ -34,3 +34,4 @@ def get_rq_retry():
retry_interval = get_config().RQ_RETRY_INTERVAL
if retry_max:
return Retry(max=retry_max, interval=retry_interval)
return None

View File

@@ -33,13 +33,13 @@ def get_table_for_model(model, name=None):
try:
return import_string(f'{model._meta.app_label}.tables.{name}')
except ImportError:
return
return None
def get_table_ordering(request, table):
"""
Given a request, return the prescribed table ordering, if any. This may be necessary to determine prior to rendering
the table itself.
Given a request, return the prescribed table ordering, if any.
This may be necessary to determine before rendering the table itself.
"""
# Check for an explicit ordering
if 'sort' in request.GET:
@@ -49,6 +49,7 @@ def get_table_ordering(request, table):
if request.user.is_authenticated:
if preference := request.user.config.get(f'tables.{table.__name__}.ordering'):
return preference
return None
def linkify_phone(value):

View File

@@ -227,12 +227,11 @@ def isodate(value):
if type(value) is datetime.date:
text = value.isoformat()
return mark_safe(f'<span title="{naturalday(value)}">{text}</span>')
elif type(value) is datetime.datetime:
if type(value) is datetime.datetime:
local_value = localtime(value) if value.tzinfo else value
text = local_value.date().isoformat()
return mark_safe(f'<span title="{naturaltime(value)}">{text}</span>')
else:
return ''
return ''
@register.filter()

View File

@@ -37,10 +37,9 @@ def widget_type(field):
"""
if hasattr(field, 'widget'):
return field.widget.__class__.__name__.lower()
elif hasattr(field, 'field'):
if hasattr(field, 'field'):
return field.field.widget.__class__.__name__.lower()
else:
return None
return None
#

View File

@@ -199,14 +199,13 @@ def humanize_speed(speed):
return ''
if speed >= 1000000000 and speed % 1000000000 == 0:
return '{} Tbps'.format(int(speed / 1000000000))
elif speed >= 1000000 and speed % 1000000 == 0:
if speed >= 1000000 and speed % 1000000 == 0:
return '{} Gbps'.format(int(speed / 1000000))
elif speed >= 1000 and speed % 1000 == 0:
if speed >= 1000 and speed % 1000 == 0:
return '{} Mbps'.format(int(speed / 1000))
elif speed >= 1000:
if speed >= 1000:
return '{} Mbps'.format(float(speed) / 1000)
else:
return '{} Kbps'.format(speed)
return '{} Kbps'.format(speed)
def _humanize_megabytes(mb, divisor=1000):
@@ -373,8 +372,7 @@ def querystring(request, **kwargs):
querystring = querydict.urlencode(safe='/')
if querystring:
return '?' + querystring
else:
return ''
return ''
@register.inclusion_tag('helpers/utilization_graph.html')

View File

@@ -66,7 +66,7 @@ class BaseFilterSetTests:
return [(f'{filter_name}_id', django_filters.ModelMultipleChoiceFilter)]
# Many-to-many relationships (forward & backward)
elif type(field) in (ManyToManyField, ManyToManyRel):
if type(field) in (ManyToManyField, ManyToManyRel):
filter_name = self.get_m2m_filter_name(field)
filter_name = self.filter_name_map.get(filter_name, filter_name)

View File

@@ -635,10 +635,9 @@ class ViewTestCases:
available = ', '.join(self.csv_data.keys())
raise ValueError(f"Scenario '{scenario_name}' not found in csv_data. Available: {available}")
return '\n'.join(self.csv_data[scenario_name])
elif isinstance(self.csv_data, (tuple, list)):
if isinstance(self.csv_data, (tuple, list)):
return '\n'.join(self.csv_data)
else:
raise TypeError(f'csv_data must be a tuple, list, or dictionary, got {type(self.csv_data)}')
raise TypeError(f'csv_data must be a tuple, list, or dictionary, got {type(self.csv_data)}')
def _get_update_csv_data(self):
return self.csv_update_data, '\n'.join(self.csv_update_data)