From eb79bd174378b2da66438e0bf27cb51eb97083fd Mon Sep 17 00:00:00 2001 From: Matthias Mair Date: Wed, 18 Oct 2023 00:06:54 +0200 Subject: [PATCH] refactor: refactor unnecessary `else` / `elif` when `if` block has a `return` statement (#5735) The use of `else` or `elif` becomes redundant and can be dropped if the last statement under the leading `if` / `elif` block is a `return` statement. In the case of an `elif` after `return`, it can be written as a separate `if` block. For `else` blocks after `return`, the statements can be shifted out of `else`. Please refer to the examples below for reference. Refactoring the code this way can improve code-readability and make it easier to maintain. Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- InvenTree/InvenTree/api.py | 6 +- InvenTree/InvenTree/conversion.py | 6 +- InvenTree/InvenTree/helpers.py | 12 ++-- InvenTree/InvenTree/middleware.py | 6 +- InvenTree/InvenTree/models.py | 9 +-- InvenTree/InvenTree/version.py | 6 +- InvenTree/InvenTree/views.py | 6 +- InvenTree/build/api.py | 21 +++---- InvenTree/build/models.py | 8 +-- InvenTree/common/admin.py | 6 +- InvenTree/common/api.py | 5 +- InvenTree/common/models.py | 16 ++--- InvenTree/common/views.py | 3 +- InvenTree/company/models.py | 9 +-- InvenTree/label/api.py | 6 +- InvenTree/order/admin.py | 15 ++--- InvenTree/order/api.py | 35 ++++------- InvenTree/order/models.py | 3 +- InvenTree/part/api.py | 59 +++++++------------ InvenTree/part/models.py | 22 +++---- .../part/templatetags/inventree_extras.py | 9 +-- .../builtin/integration/currency_exchange.py | 6 +- .../plugin/builtin/labels/inventree_label.py | 3 +- InvenTree/plugin/plugin.py | 3 +- InvenTree/plugin/registry.py | 3 +- InvenTree/report/templatetags/report.py | 12 ++-- InvenTree/stock/api.py | 52 ++++++---------- InvenTree/stock/models.py | 8 +-- InvenTree/users/models.py | 3 +- 29 files changed, 123 insertions(+), 235 deletions(-) diff --git a/InvenTree/InvenTree/api.py b/InvenTree/InvenTree/api.py index c269cd5eb1..b1947e1582 100644 --- a/InvenTree/InvenTree/api.py +++ b/InvenTree/InvenTree/api.py @@ -207,10 +207,8 @@ class APIDownloadMixin: if export_format and export_format in ['csv', 'tsv', 'xls', 'xlsx']: queryset = self.filter_queryset(self.get_queryset()) return self.download_queryset(queryset, export_format) - - else: - # Default to the parent class implementation - return super().get(request, *args, **kwargs) + # Default to the parent class implementation + return super().get(request, *args, **kwargs) def download_queryset(self, queryset, export_format): """This function must be implemented to provide a downloadFile request.""" diff --git a/InvenTree/InvenTree/conversion.py b/InvenTree/InvenTree/conversion.py index 6275b00c15..e42d182755 100644 --- a/InvenTree/InvenTree/conversion.py +++ b/InvenTree/InvenTree/conversion.py @@ -20,8 +20,7 @@ def get_unit_registry(): # Cache the unit registry for speedier access if _unit_registry is None: return reload_unit_registry() - else: - return _unit_registry + return _unit_registry def reload_unit_registry(): @@ -145,8 +144,7 @@ def convert_physical_value(value: str, unit: str = None, strip_units=True): return magnitude elif unit or value.units: return ureg.Quantity(magnitude, unit or value.units) - else: - return ureg.Quantity(magnitude) + return ureg.Quantity(magnitude) def is_dimensionless(value): diff --git a/InvenTree/InvenTree/helpers.py b/InvenTree/InvenTree/helpers.py index b48ff1f6b1..a59b9fe26a 100644 --- a/InvenTree/InvenTree/helpers.py +++ b/InvenTree/InvenTree/helpers.py @@ -107,15 +107,13 @@ def getLogoImage(as_file=False, custom=True): if storage is not None: if as_file: return f"file://{storage.path(settings.CUSTOM_LOGO)}" - else: - return storage.url(settings.CUSTOM_LOGO) + return storage.url(settings.CUSTOM_LOGO) # If we have got to this point, return the default logo if as_file: path = settings.STATIC_ROOT.joinpath('img/inventree.png') return f"file://{path}" - else: - return getStaticUrl('img/inventree.png') + return getStaticUrl('img/inventree.png') def getSplashScreen(custom=True): @@ -156,8 +154,7 @@ def str2bool(text, test=True): """ if test: return str(text).lower() in ['1', 'y', 'yes', 't', 'true', 'ok', 'on', ] - else: - return str(text).lower() in ['0', 'n', 'no', 'none', 'f', 'false', 'off', ] + return str(text).lower() in ['0', 'n', 'no', 'none', 'f', 'false', 'off', ] def str2int(text, default=None): @@ -182,8 +179,7 @@ def is_bool(text): return True elif str2bool(text, False): return True - else: - return False + return False def isNull(text): diff --git a/InvenTree/InvenTree/middleware.py b/InvenTree/InvenTree/middleware.py index a6c2a0c435..6a365d82de 100644 --- a/InvenTree/InvenTree/middleware.py +++ b/InvenTree/InvenTree/middleware.py @@ -108,10 +108,8 @@ class AuthRequiredMiddleware(object): # Save the 'next' parameter to pass through to the login view return redirect(f'{reverse_lazy("account_login")}?next={request.path}') - - else: - # Return a 401 (Unauthorized) response code for this request - return HttpResponse('Unauthorized', status=401) + # Return a 401 (Unauthorized) response code for this request + return HttpResponse('Unauthorized', status=401) response = self.get_response(request) diff --git a/InvenTree/InvenTree/models.py b/InvenTree/InvenTree/models.py index 3bc9d58f31..4e939a9da1 100644 --- a/InvenTree/InvenTree/models.py +++ b/InvenTree/InvenTree/models.py @@ -231,8 +231,7 @@ class ReferenceIndexingMixin(models.Model): if query.exists(): return query.first() - else: - return None + return None @classmethod def get_next_reference(cls): @@ -471,8 +470,7 @@ class InvenTreeAttachment(models.Model): """Human name for attachment.""" if self.attachment is not None: return os.path.basename(self.attachment.name) - else: - return str(self.link) + return str(self.link) attachment = models.FileField(upload_to=rename_attachment, verbose_name=_('Attachment'), help_text=_('Select file to attach'), @@ -502,8 +500,7 @@ class InvenTreeAttachment(models.Model): """Base name/path for attachment.""" if self.attachment: return os.path.basename(self.attachment.name) - else: - return None + return None @basename.setter def basename(self, fn): diff --git a/InvenTree/InvenTree/version.py b/InvenTree/InvenTree/version.py index 839e6ea4a0..c8d2f4216b 100644 --- a/InvenTree/InvenTree/version.py +++ b/InvenTree/InvenTree/version.py @@ -41,8 +41,7 @@ def inventreeInstanceTitle(): if common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE_TITLE", False): return common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE", "") - else: - return 'InvenTree' + return 'InvenTree' def inventreeVersion(): @@ -73,8 +72,7 @@ def inventreeDocsVersion(): """ if isInvenTreeDevelopmentVersion(): return "latest" - else: - return INVENTREE_SW_VERSION # pragma: no cover + return INVENTREE_SW_VERSION # pragma: no cover def isInvenTreeUpToDate(): diff --git a/InvenTree/InvenTree/views.py b/InvenTree/InvenTree/views.py index cec4753f61..9a6f4e95f2 100644 --- a/InvenTree/InvenTree/views.py +++ b/InvenTree/InvenTree/views.py @@ -43,8 +43,7 @@ def auth_request(request): """ if request.user.is_authenticated: return HttpResponse(status=200) - else: - return HttpResponse(status=403) + return HttpResponse(status=403) class InvenTreeRoleMixin(PermissionRequiredMixin): @@ -222,8 +221,7 @@ class AjaxMixin(InvenTreeRoleMixin): """ if method == 'POST': return self.request.POST.get(name, None) - else: - return self.request.GET.get(name, None) + return self.request.GET.get(name, None) def get_data(self): """Get extra context data (default implementation is empty dict). diff --git a/InvenTree/build/api.py b/InvenTree/build/api.py index 21d6ac666e..f7385c39c5 100644 --- a/InvenTree/build/api.py +++ b/InvenTree/build/api.py @@ -46,8 +46,7 @@ class BuildFilter(rest_filters.FilterSet): """Filter the queryset to either include or exclude orders which are active.""" if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES) - else: - return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES) + return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES) overdue = rest_filters.BooleanFilter(label='Build is overdue', method='filter_overdue') @@ -55,8 +54,7 @@ class BuildFilter(rest_filters.FilterSet): """Filter the queryset to either include or exclude orders which are overdue.""" if str2bool(value): return queryset.filter(Build.OVERDUE_FILTER) - else: - return queryset.exclude(Build.OVERDUE_FILTER) + return queryset.exclude(Build.OVERDUE_FILTER) assigned_to_me = rest_filters.BooleanFilter(label='assigned_to_me', method='filter_assigned_to_me') @@ -69,8 +67,7 @@ class BuildFilter(rest_filters.FilterSet): if value: return queryset.filter(responsible__in=owners) - else: - return queryset.exclude(responsible__in=owners) + return queryset.exclude(responsible__in=owners) assigned_to = rest_filters.NumberFilter(label='responsible', method='filter_responsible') @@ -102,8 +99,7 @@ class BuildFilter(rest_filters.FilterSet): """Filter by whether or not the order has a project code""" if str2bool(value): return queryset.exclude(project_code=None) - else: - return queryset.filter(project_code=None) + return queryset.filter(project_code=None) class BuildList(APIDownloadMixin, ListCreateAPI): @@ -292,8 +288,7 @@ class BuildLineFilter(rest_filters.FilterSet): """Filter by whether each BuildLine is fully allocated""" if str2bool(value): return queryset.filter(allocated__gte=F('quantity')) - else: - return queryset.filter(allocated__lt=F('quantity')) + return queryset.filter(allocated__lt=F('quantity')) available = rest_filters.BooleanFilter(label=_('Available'), method='filter_available') @@ -310,8 +305,7 @@ class BuildLineFilter(rest_filters.FilterSet): if str2bool(value): return queryset.filter(flt) - else: - return queryset.exclude(flt) + return queryset.exclude(flt) class BuildLineEndpoint: @@ -508,8 +502,7 @@ class BuildItemFilter(rest_filters.FilterSet): """Filter the queryset based on whether build items are tracked""" if str2bool(value): return queryset.exclude(install_into=None) - else: - return queryset.filter(install_into=None) + return queryset.filter(install_into=None) class BuildItemList(ListCreateAPI): diff --git a/InvenTree/build/models.py b/InvenTree/build/models.py index 5be28f6775..e051f23bc6 100644 --- a/InvenTree/build/models.py +++ b/InvenTree/build/models.py @@ -314,9 +314,8 @@ class Build(MPTTModel, InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models. """Return all Build Order objects under this one.""" if cascade: return Build.objects.filter(parent=self.pk) - else: - descendants = self.get_descendants(include_self=True) - Build.objects.filter(parent__pk__in=[d.pk for d in descendants]) + descendants = self.get_descendants(include_self=True) + Build.objects.filter(parent__pk__in=[d.pk for d in descendants]) def sub_build_count(self, cascade=True): """Return the number of sub builds under this one. @@ -957,8 +956,7 @@ class Build(MPTTModel, InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models. return 1 elif item.part in variant_parts: return 2 - else: - return 3 + return 3 new_items = [] diff --git a/InvenTree/common/admin.py b/InvenTree/common/admin.py index c2c3939b9b..cbc5b6621b 100644 --- a/InvenTree/common/admin.py +++ b/InvenTree/common/admin.py @@ -16,8 +16,7 @@ class SettingsAdmin(ImportExportModelAdmin): """Prevent the 'key' field being edited once the setting is created.""" if obj: return ['key'] - else: - return [] + return [] class UserSettingsAdmin(ImportExportModelAdmin): @@ -29,8 +28,7 @@ class UserSettingsAdmin(ImportExportModelAdmin): """Prevent the 'key' field being edited once the setting is created.""" if obj: return ['key'] - else: - return [] + return [] class WebhookAdmin(ImportExportModelAdmin): diff --git a/InvenTree/common/api.py b/InvenTree/common/api.py index 63bd11d900..23536f2aeb 100644 --- a/InvenTree/common/api.py +++ b/InvenTree/common/api.py @@ -206,9 +206,8 @@ class GlobalSettingsPermissions(permissions.BasePermission): if request.method in ['GET', 'HEAD', 'OPTIONS']: return True - else: - # Any other methods require staff access permissions - return user.is_staff + # Any other methods require staff access permissions + return user.is_staff except AttributeError: # pragma: no cover return False diff --git a/InvenTree/common/models.py b/InvenTree/common/models.py index c62577bc09..340ecc83a1 100644 --- a/InvenTree/common/models.py +++ b/InvenTree/common/models.py @@ -404,8 +404,7 @@ class BaseInvenTreeSetting(models.Model): if settings is not None and key in settings: return settings[key] - else: - return {} + return {} @classmethod def get_setting_name(cls, key, **kwargs): @@ -458,8 +457,7 @@ class BaseInvenTreeSetting(models.Model): if callable(default): return default() - else: - return default + return default @classmethod def get_setting_choices(cls, key, **kwargs): @@ -881,9 +879,7 @@ class BaseInvenTreeSetting(models.Model): elif self.is_model(): return 'related field' - - else: - return 'string' + return 'string' @classmethod def validator_is_bool(cls, validator): @@ -1891,8 +1887,7 @@ class InvenTreeSetting(BaseInvenTreeSetting): if options: return options.get('requires_restart', False) - else: - return False + return False def label_printer_options(): @@ -2430,8 +2425,7 @@ def get_price(instance, quantity, moq=True, multiples=True, currency=None, break if pb_found: cost = pb_cost * quantity return InvenTree.helpers.normalize(cost + instance.base_cost) - else: - return None + return None class ColorTheme(models.Model): diff --git a/InvenTree/common/views.py b/InvenTree/common/views.py index 62e8011141..2eeb48b5df 100644 --- a/InvenTree/common/views.py +++ b/InvenTree/common/views.py @@ -480,8 +480,7 @@ class FileManagementAjaxView(AjaxView): self.render_done(form) data = {'form_valid': True, 'success': _('Parts imported')} return self.renderJsonResponse(request, data=data) - else: - self.storage.current_step = self.steps.next + self.storage.current_step = self.steps.next return self.renderJsonResponse(request, data={'form_valid': None}) diff --git a/InvenTree/company/models.py b/InvenTree/company/models.py index 0b0bfba960..4947f6fb63 100644 --- a/InvenTree/company/models.py +++ b/InvenTree/company/models.py @@ -195,15 +195,13 @@ class Company(InvenTreeNotesMixin, MetadataMixin, models.Model): """Return the URL of the image for this company.""" if self.image: return InvenTree.helpers.getMediaUrl(self.image.url) - else: - return InvenTree.helpers.getBlankImage() + return InvenTree.helpers.getBlankImage() def get_thumbnail_url(self): """Return the URL for the thumbnail image for this Company.""" if self.image: return InvenTree.helpers.getMediaUrl(self.image.thumbnail.url) - else: - return InvenTree.helpers.getBlankThumbnail() + return InvenTree.helpers.getBlankThumbnail() @property def parts(self): @@ -849,8 +847,7 @@ class SupplierPart(MetadataMixin, InvenTreeBarcodeMixin, common.models.MetaMixin if q is None or r is None: return 0 - else: - return max(q - r, 0) + return max(q - r, 0) def purchase_orders(self): """Returns a list of purchase orders relating to this supplier part.""" diff --git a/InvenTree/label/api.py b/InvenTree/label/api.py index 65fb1d38a3..c4a722b4aa 100644 --- a/InvenTree/label/api.py +++ b/InvenTree/label/api.py @@ -171,8 +171,7 @@ class LabelPrintMixin(LabelFilterMixin): if plugin.is_active(): # Only return the plugin if it is enabled! return plugin - else: - raise ValidationError(f"Plugin '{plugin_key}' is not enabled") + raise ValidationError(f"Plugin '{plugin_key}' is not enabled") else: raise NotFound(f"Plugin '{plugin_key}' not found") @@ -196,8 +195,7 @@ class LabelPrintMixin(LabelFilterMixin): if isinstance(result, JsonResponse): result['plugin'] = plugin.plugin_slug() return result - else: - raise ValidationError(f"Plugin '{plugin.plugin_slug()}' returned invalid response type '{type(result)}'") + raise ValidationError(f"Plugin '{plugin.plugin_slug()}' returned invalid response type '{type(result)}'") class StockItemLabelMixin: diff --git a/InvenTree/order/admin.py b/InvenTree/order/admin.py index 838bb6bf53..b432e36154 100644 --- a/InvenTree/order/admin.py +++ b/InvenTree/order/admin.py @@ -20,8 +20,7 @@ class ProjectCodeResourceMixin: """Return the project code value, not the pk""" if order.project_code: return order.project_code.code - else: - return '' + return '' class TotalPriceResourceMixin: @@ -33,8 +32,7 @@ class TotalPriceResourceMixin: """Return the total price amount, not the object itself""" if order.total_price: return order.total_price.amount - else: - return '' + return '' class PriceResourceMixin: @@ -46,8 +44,7 @@ class PriceResourceMixin: """Return the price amount, not the object itself""" if line.price: return line.price.amount - else: - return '' + return '' # region general classes @@ -175,8 +172,7 @@ class PurchaseOrderLineItemResource(PriceResourceMixin, InvenTreeResource): """Return a string value of the 'purchase_price' field, rather than the 'Money' object""" if line.purchase_price: return line.purchase_price.amount - else: - return '' + return '' class PurchaseOrderExtraLineResource(PriceResourceMixin, InvenTreeResource): @@ -232,8 +228,7 @@ class SalesOrderLineItemResource(PriceResourceMixin, InvenTreeResource): """ if item.sale_price: return str(item.sale_price) - else: - return '' + return '' class SalesOrderExtraLineResource(PriceResourceMixin, InvenTreeResource): diff --git a/InvenTree/order/api.py b/InvenTree/order/api.py index 2f9202d625..4e6b859aa2 100644 --- a/InvenTree/order/api.py +++ b/InvenTree/order/api.py @@ -110,8 +110,7 @@ class OrderFilter(rest_filters.FilterSet): if str2bool(value): return queryset.filter(responsible__in=owners) - else: - return queryset.exclude(responsible__in=owners) + return queryset.exclude(responsible__in=owners) overdue = rest_filters.BooleanFilter(label='overdue', method='filter_overdue') @@ -122,8 +121,7 @@ class OrderFilter(rest_filters.FilterSet): """ if str2bool(value): return queryset.filter(self.Meta.model.overdue_filter()) - else: - return queryset.exclude(self.Meta.model.overdue_filter()) + return queryset.exclude(self.Meta.model.overdue_filter()) outstanding = rest_filters.BooleanFilter(label='outstanding', method='filter_outstanding') @@ -131,8 +129,7 @@ class OrderFilter(rest_filters.FilterSet): """Generic filter for determining if an order is 'outstanding'""" if str2bool(value): return queryset.filter(status__in=self.Meta.model.get_status_class().OPEN) - else: - return queryset.exclude(status__in=self.Meta.model.get_status_class().OPEN) + return queryset.exclude(status__in=self.Meta.model.get_status_class().OPEN) project_code = rest_filters.ModelChoiceFilter( queryset=common_models.ProjectCode.objects.all(), @@ -145,8 +142,7 @@ class OrderFilter(rest_filters.FilterSet): """Filter by whether or not the order has a project code""" if str2bool(value): return queryset.exclude(project_code=None) - else: - return queryset.filter(project_code=None) + return queryset.filter(project_code=None) class LineItemFilter(rest_filters.FilterSet): @@ -163,8 +159,7 @@ class LineItemFilter(rest_filters.FilterSet): if str2bool(value): return queryset.exclude(**filters) - else: - return queryset.filter(**filters) + return queryset.filter(**filters) class PurchaseOrderFilter(OrderFilter): @@ -427,8 +422,7 @@ class PurchaseOrderLineItemFilter(LineItemFilter): """Filter by "pending" status (order status = pending)""" if str2bool(value): return queryset.filter(order__status__in=PurchaseOrderStatusGroups.OPEN) - else: - return queryset.exclude(order__status__in=PurchaseOrderStatusGroups.OPEN) + return queryset.exclude(order__status__in=PurchaseOrderStatusGroups.OPEN) received = rest_filters.BooleanFilter(label='received', method='filter_received') @@ -441,9 +435,8 @@ class PurchaseOrderLineItemFilter(LineItemFilter): if str2bool(value): return queryset.filter(q) - else: - # Only count "pending" orders - return queryset.exclude(q).filter(order__status__in=PurchaseOrderStatusGroups.OPEN) + # Only count "pending" orders + return queryset.exclude(q).filter(order__status__in=PurchaseOrderStatusGroups.OPEN) class PurchaseOrderLineItemMixin: @@ -749,8 +742,7 @@ class SalesOrderLineItemFilter(LineItemFilter): if str2bool(value): return queryset.filter(q) - else: - return queryset.exclude(q) + return queryset.exclude(q) class SalesOrderLineItemMixin: @@ -1003,8 +995,7 @@ class SalesOrderShipmentFilter(rest_filters.FilterSet): """Filter SalesOrder list by 'shipped' status (boolean)""" if str2bool(value): return queryset.exclude(shipment_date=None) - else: - return queryset.filter(shipment_date=None) + return queryset.filter(shipment_date=None) delivered = rest_filters.BooleanFilter(label='delivered', method='filter_delivered') @@ -1012,8 +1003,7 @@ class SalesOrderShipmentFilter(rest_filters.FilterSet): """Filter SalesOrder list by 'delivered' status (boolean)""" if str2bool(value): return queryset.exclude(delivery_date=None) - else: - return queryset.filter(delivery_date=None) + return queryset.filter(delivery_date=None) class SalesOrderShipmentList(ListCreateAPI): @@ -1240,8 +1230,7 @@ class ReturnOrderLineItemFilter(LineItemFilter): """Filter by 'received' field""" if str2bool(value): return queryset.exclude(received_date=None) - else: - return queryset.filter(received_date=None) + return queryset.filter(received_date=None) class ReturnOrderLineItemMixin: diff --git a/InvenTree/order/models.py b/InvenTree/order/models.py index 297982d7c8..75f6aaacb4 100644 --- a/InvenTree/order/models.py +++ b/InvenTree/order/models.py @@ -1184,8 +1184,7 @@ class PurchaseOrderLineItem(OrderLineItem): """ if self.part is None: return None - else: - return self.part.part + return self.part.part part = models.ForeignKey( SupplierPart, on_delete=models.SET_NULL, diff --git a/InvenTree/part/api.py b/InvenTree/part/api.py index 5670b2c82e..0072fdd3e2 100644 --- a/InvenTree/part/api.py +++ b/InvenTree/part/api.py @@ -820,8 +820,7 @@ class PartFilter(rest_filters.FilterSet): """Filter by whether the Part has units or not""" if str2bool(value): return queryset.exclude(units='') - else: - return queryset.filter(units='') + return queryset.filter(units='') # Filter by parts which have (or not) an IPN value has_ipn = rest_filters.BooleanFilter(label='Has IPN', method='filter_has_ipn') @@ -830,8 +829,7 @@ class PartFilter(rest_filters.FilterSet): """Filter by whether the Part has an IPN (internal part number) or not""" if str2bool(value): return queryset.exclude(IPN='') - else: - return queryset.filter(IPN='') + return queryset.filter(IPN='') # Regex filter for name name_regex = rest_filters.CharFilter(label='Filter by name (regex)', field_name='name', lookup_expr='iregex') @@ -855,9 +853,8 @@ class PartFilter(rest_filters.FilterSet): # Ignore any parts which do not have a specified 'minimum_stock' level # Filter items which have an 'in_stock' level lower than 'minimum_stock' return queryset.exclude(minimum_stock=0).filter(Q(total_in_stock__lt=F('minimum_stock'))) - else: - # Filter items which have an 'in_stock' level higher than 'minimum_stock' - return queryset.filter(Q(total_in_stock__gte=F('minimum_stock'))) + # Filter items which have an 'in_stock' level higher than 'minimum_stock' + return queryset.filter(Q(total_in_stock__gte=F('minimum_stock'))) # has_stock filter has_stock = rest_filters.BooleanFilter(label='Has stock', method='filter_has_stock') @@ -866,8 +863,7 @@ class PartFilter(rest_filters.FilterSet): """Filter by whether the Part has any stock""" if str2bool(value): return queryset.filter(Q(in_stock__gt=0)) - else: - return queryset.filter(Q(in_stock__lte=0)) + return queryset.filter(Q(in_stock__lte=0)) # unallocated_stock filter unallocated_stock = rest_filters.BooleanFilter(label='Unallocated stock', method='filter_unallocated_stock') @@ -876,8 +872,7 @@ class PartFilter(rest_filters.FilterSet): """Filter by whether the Part has unallocated stock""" if str2bool(value): return queryset.filter(Q(unallocated_stock__gt=0)) - else: - return queryset.filter(Q(unallocated_stock__lte=0)) + return queryset.filter(Q(unallocated_stock__lte=0)) convert_from = rest_filters.ModelChoiceFilter(label="Can convert from", queryset=Part.objects.all(), method='filter_convert_from') @@ -926,8 +921,7 @@ class PartFilter(rest_filters.FilterSet): if str2bool(value): return queryset.exclude(q_a | q_b) - else: - return queryset.filter(q_a | q_b) + return queryset.filter(q_a | q_b) stocktake = rest_filters.BooleanFilter(label="Has stocktake", method='filter_has_stocktake') @@ -935,8 +929,7 @@ class PartFilter(rest_filters.FilterSet): """Filter the queryset based on whether stocktake data is available""" if str2bool(value): return queryset.exclude(last_stocktake=None) - else: - return queryset.filter(last_stocktake=None) + return queryset.filter(last_stocktake=None) stock_to_build = rest_filters.BooleanFilter(label='Required for Build Order', method='filter_stock_to_build') @@ -945,9 +938,8 @@ class PartFilter(rest_filters.FilterSet): if str2bool(value): # Return parts which are required for a build order, but have not yet been allocated return queryset.filter(required_for_build_orders__gt=F('allocated_to_build_orders')) - else: - # Return parts which are not required for a build order, or have already been allocated - return queryset.filter(required_for_build_orders__lte=F('allocated_to_build_orders')) + # Return parts which are not required for a build order, or have already been allocated + return queryset.filter(required_for_build_orders__lte=F('allocated_to_build_orders')) depleted_stock = rest_filters.BooleanFilter(label='Depleted Stock', method='filter_depleted_stock') @@ -955,8 +947,7 @@ class PartFilter(rest_filters.FilterSet): """Filter the queryset based on whether the part is fully depleted of stock""" if str2bool(value): return queryset.filter(Q(in_stock=0) & ~Q(stock_item_count=0)) - else: - return queryset.exclude(Q(in_stock=0) & ~Q(stock_item_count=0)) + return queryset.exclude(Q(in_stock=0) & ~Q(stock_item_count=0)) is_template = rest_filters.BooleanFilter() @@ -1075,8 +1066,7 @@ class PartList(PartMixin, APIDownloadMixin, ListCreateAPI): return self.get_paginated_response(data) elif request.is_ajax(): return JsonResponse(data, safe=False) - else: - return Response(data) + return Response(data) def filter_queryset(self, queryset): """Perform custom filtering of the queryset""" @@ -1280,10 +1270,9 @@ class PartDetail(PartMixin, RetrieveUpdateDestroyAPI): if not part.active: # Delete return super(PartDetail, self).destroy(request, *args, **kwargs) - else: - # Return 405 error - message = 'Part is active: cannot delete' - return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, data=message) + # Return 405 error + message = 'Part is active: cannot delete' + return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, data=message) def update(self, request, *args, **kwargs): """Custom update functionality for Part instance. @@ -1360,8 +1349,7 @@ class PartParameterTemplateFilter(rest_filters.FilterSet): """Filter queryset to include only PartParameterTemplates with choices.""" if str2bool(value): return queryset.exclude(Q(choices=None) | Q(choices='')) - else: - return queryset.filter(Q(choices=None) | Q(choices='')) + return queryset.filter(Q(choices=None) | Q(choices='')) has_units = rest_filters.BooleanFilter( method='filter_has_units', @@ -1372,8 +1360,7 @@ class PartParameterTemplateFilter(rest_filters.FilterSet): """Filter queryset to include only PartParameterTemplates with units.""" if str2bool(value): return queryset.exclude(Q(units=None) | Q(units='')) - else: - return queryset.filter(Q(units=None) | Q(units='')) + return queryset.filter(Q(units=None) | Q(units='')) class PartParameterTemplateList(ListCreateAPI): @@ -1656,8 +1643,7 @@ class BomFilter(rest_filters.FilterSet): """Filter the queryset based on whether each line item has any available stock""" if str2bool(value): return queryset.filter(available_stock__gt=0) - else: - return queryset.filter(available_stock=0) + return queryset.filter(available_stock=0) on_order = rest_filters.BooleanFilter(label="On order", method="filter_on_order") @@ -1665,8 +1651,7 @@ class BomFilter(rest_filters.FilterSet): """Filter the queryset based on whether each line item has any stock on order""" if str2bool(value): return queryset.filter(on_order__gt=0) - else: - return queryset.filter(on_order=0) + return queryset.filter(on_order=0) has_pricing = rest_filters.BooleanFilter(label="Has Pricing", method="filter_has_pricing") @@ -1677,8 +1662,7 @@ class BomFilter(rest_filters.FilterSet): if str2bool(value): return queryset.exclude(q_a | q_b) - else: - return queryset.filter(q_a | q_b) + return queryset.filter(q_a | q_b) class BomMixin: @@ -1751,8 +1735,7 @@ class BomList(BomMixin, ListCreateDestroyAPIView): return self.get_paginated_response(data) elif request.is_ajax(): return JsonResponse(data, safe=False) - else: - return Response(data) + return Response(data) def filter_queryset(self, queryset): """Custom query filtering for the BomItem list API""" diff --git a/InvenTree/part/models.py b/InvenTree/part/models.py index ac6b8c123e..854deba245 100644 --- a/InvenTree/part/models.py +++ b/InvenTree/part/models.py @@ -765,15 +765,13 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel) """Return the URL of the image for this part.""" if self.image: return helpers.getMediaUrl(self.image.url) - else: - return helpers.getBlankImage() + return helpers.getBlankImage() def get_thumbnail_url(self): """Return the URL of the image thumbnail for this part.""" if self.image: return helpers.getMediaUrl(self.image.thumbnail.url) - else: - return helpers.getBlankThumbnail() + return helpers.getBlankThumbnail() def validate_unique(self, exclude=None): """Validate that this Part instance is 'unique'. @@ -1906,12 +1904,10 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel) elif bom_price_range is None: return buy_price_range - - else: - return ( - min(buy_price_range[0], bom_price_range[0]), - max(buy_price_range[1], bom_price_range[1]) - ) + return ( + min(buy_price_range[0], bom_price_range[0]), + max(buy_price_range[1], bom_price_range[1]) + ) base_cost = models.DecimalField(max_digits=19, decimal_places=6, default=0, validators=[MinValueValidator(0)], verbose_name=_('base cost'), help_text=_('Minimum charge (e.g. stocking fee)')) @@ -3102,8 +3098,7 @@ class PartStocktakeReport(models.Model): """Return the URL for the associaed report file for download""" if self.report: return self.report.url - else: - return None + return None date = models.DateField( verbose_name=_('Date'), @@ -3644,8 +3639,7 @@ class PartCategoryParameterTemplate(MetadataMixin, models.Model): """String representation of a PartCategoryParameterTemplate (admin interface).""" if self.default_value: return f'{self.category.name} | {self.parameter_template.name} | {self.default_value}' - else: - return f'{self.category.name} | {self.parameter_template.name}' + return f'{self.category.name} | {self.parameter_template.name}' category = models.ForeignKey(PartCategory, on_delete=models.CASCADE, diff --git a/InvenTree/part/templatetags/inventree_extras.py b/InvenTree/part/templatetags/inventree_extras.py index 35ed4336c6..7abd1816ef 100644 --- a/InvenTree/part/templatetags/inventree_extras.py +++ b/InvenTree/part/templatetags/inventree_extras.py @@ -486,10 +486,8 @@ def primitive_to_javascript(primitive): elif type(primitive) in [int, float]: return primitive - - else: - # Wrap with quotes - return format_html("'{}'", primitive) # noqa: P103 + # Wrap with quotes + return format_html("'{}'", primitive) # noqa: P103 @register.simple_tag() @@ -497,8 +495,7 @@ def js_bool(val): """Return a javascript boolean value (true or false)""" if val: return 'true' - else: - return 'false' + return 'false' @register.filter diff --git a/InvenTree/plugin/builtin/integration/currency_exchange.py b/InvenTree/plugin/builtin/integration/currency_exchange.py index f853b472ee..33788c0ba2 100644 --- a/InvenTree/plugin/builtin/integration/currency_exchange.py +++ b/InvenTree/plugin/builtin/integration/currency_exchange.py @@ -41,10 +41,8 @@ class InvenTreeCurrencyExchange(APICallMixin, CurrencyExchangeMixin, InvenTreePl rates[base_currency] = 1.00 return rates - - else: - logger.warning("Failed to update exchange rates from %s: Server returned status %s", self.api_url, response.status_code) - return None + logger.warning("Failed to update exchange rates from %s: Server returned status %s", self.api_url, response.status_code) + return None @property def api_url(self): diff --git a/InvenTree/plugin/builtin/labels/inventree_label.py b/InvenTree/plugin/builtin/labels/inventree_label.py index cd052aee14..a48f5bd04c 100644 --- a/InvenTree/plugin/builtin/labels/inventree_label.py +++ b/InvenTree/plugin/builtin/labels/inventree_label.py @@ -90,5 +90,4 @@ class InvenTreeLabelPlugin(LabelPrintingMixin, SettingsMixin, InvenTreePlugin): if debug: return self.render_to_html(label, request, **kwargs) - else: - return self.render_to_pdf(label, request, **kwargs) + return self.render_to_pdf(label, request, **kwargs) diff --git a/InvenTree/plugin/plugin.py b/InvenTree/plugin/plugin.py index 16ac0ff03d..1938f59a2a 100644 --- a/InvenTree/plugin/plugin.py +++ b/InvenTree/plugin/plugin.py @@ -114,8 +114,7 @@ class MetaBase: if config: return config.active - else: - return False # pragma: no cover + return False # pragma: no cover class MixinBase: diff --git a/InvenTree/plugin/registry.py b/InvenTree/plugin/registry.py index 5e9c29eb61..9f89c1e777 100644 --- a/InvenTree/plugin/registry.py +++ b/InvenTree/plugin/registry.py @@ -403,8 +403,7 @@ class PluginsRegistry: if install_plugins_file(): settings.PLUGIN_FILE_CHECKED = True return 'first_run' - else: - return False + return False # endregion diff --git a/InvenTree/report/templatetags/report.py b/InvenTree/report/templatetags/report.py index 28a96f0d44..7673b9808d 100644 --- a/InvenTree/report/templatetags/report.py +++ b/InvenTree/report/templatetags/report.py @@ -64,8 +64,7 @@ def getkey(container: dict, key): if key in container: return container[key] - else: - return None + return None @register.simple_tag() @@ -93,8 +92,7 @@ def asset(filename): if debug_mode: return os.path.join(settings.MEDIA_URL, 'report', 'assets', filename) - else: - return f"file://{full_path}" + return f"file://{full_path}" @register.simple_tag() @@ -137,8 +135,7 @@ def uploaded_image(filename, replace_missing=True, replacement_file='blank_image # In debug mode, return a web path if exists: return os.path.join(settings.MEDIA_URL, filename) - else: - return os.path.join(settings.STATIC_URL, 'img', replacement_file) + return os.path.join(settings.STATIC_URL, 'img', replacement_file) else: # Return file path if exists: @@ -209,8 +206,7 @@ def part_parameter(part: Part, parameter_name: str): """ if type(part) is Part: return part.get_parameter(parameter_name) - else: - return None + return None @register.simple_tag() diff --git a/InvenTree/stock/api.py b/InvenTree/stock/api.py index 581b7417ce..903861f4ea 100644 --- a/InvenTree/stock/api.py +++ b/InvenTree/stock/api.py @@ -236,8 +236,7 @@ class StockLocationFilter(rest_filters.FilterSet): """Filter by whether or not the location has a location type""" if str2bool(value): return queryset.exclude(location_type=None) - else: - return queryset.filter(location_type=None) + return queryset.filter(location_type=None) class StockLocationList(APIDownloadMixin, ListCreateAPI): @@ -483,9 +482,8 @@ class StockFilter(rest_filters.FilterSet): if str2bool(value): # Filter StockItem with either build allocations or sales order allocations return queryset.filter(Q(sales_order_allocations__isnull=False) | Q(allocations__isnull=False)) - else: - # Filter StockItem without build allocations or sales order allocations - return queryset.filter(Q(sales_order_allocations__isnull=True) & Q(allocations__isnull=True)) + # Filter StockItem without build allocations or sales order allocations + return queryset.filter(Q(sales_order_allocations__isnull=True) & Q(allocations__isnull=True)) expired = rest_filters.BooleanFilter(label='Expired', method='filter_expired') @@ -496,8 +494,7 @@ class StockFilter(rest_filters.FilterSet): if str2bool(value): return queryset.filter(StockItem.EXPIRED_FILTER) - else: - return queryset.exclude(StockItem.EXPIRED_FILTER) + return queryset.exclude(StockItem.EXPIRED_FILTER) external = rest_filters.BooleanFilter(label=_('External Location'), method='filter_external') @@ -505,8 +502,7 @@ class StockFilter(rest_filters.FilterSet): """Filter by whether or not the stock item is located in an external location""" if str2bool(value): return queryset.filter(location__external=True) - else: - return queryset.exclude(location__external=True) + return queryset.exclude(location__external=True) in_stock = rest_filters.BooleanFilter(label='In Stock', method='filter_in_stock') @@ -514,8 +510,7 @@ class StockFilter(rest_filters.FilterSet): """Filter by if item is in stock.""" if str2bool(value): return queryset.filter(StockItem.IN_STOCK_FILTER) - else: - return queryset.exclude(StockItem.IN_STOCK_FILTER) + return queryset.exclude(StockItem.IN_STOCK_FILTER) available = rest_filters.BooleanFilter(label='Available', method='filter_available') @@ -528,9 +523,8 @@ class StockFilter(rest_filters.FilterSet): # The 'quantity' field is greater than the calculated 'allocated' field # Note that the item must also be "in stock" return queryset.filter(StockItem.IN_STOCK_FILTER).filter(Q(quantity__gt=F('allocated'))) - else: - # The 'quantity' field is less than (or equal to) the calculated 'allocated' field - return queryset.filter(Q(quantity__lte=F('allocated'))) + # The 'quantity' field is less than (or equal to) the calculated 'allocated' field + return queryset.filter(Q(quantity__lte=F('allocated'))) batch = rest_filters.CharFilter(label="Batch code filter (case insensitive)", lookup_expr='iexact') @@ -552,8 +546,7 @@ class StockFilter(rest_filters.FilterSet): if str2bool(value): return queryset.exclude(q) - else: - return queryset.filter(q) + return queryset.filter(q) has_batch = rest_filters.BooleanFilter(label='Has batch code', method='filter_has_batch') @@ -563,8 +556,7 @@ class StockFilter(rest_filters.FilterSet): if str2bool(value): return queryset.exclude(q) - else: - return queryset.filter(q) + return queryset.filter(q) tracked = rest_filters.BooleanFilter(label='Tracked', method='filter_tracked') @@ -580,8 +572,7 @@ class StockFilter(rest_filters.FilterSet): if str2bool(value): return queryset.exclude(q_batch & q_serial) - else: - return queryset.filter(q_batch & q_serial) + return queryset.filter(q_batch & q_serial) installed = rest_filters.BooleanFilter(label='Installed in other stock item', method='filter_installed') @@ -589,8 +580,7 @@ class StockFilter(rest_filters.FilterSet): """Filter stock items by "belongs_to" field being empty.""" if str2bool(value): return queryset.exclude(belongs_to=None) - else: - return queryset.filter(belongs_to=None) + return queryset.filter(belongs_to=None) has_installed_items = rest_filters.BooleanFilter(label='Has installed items', method='filter_has_installed') @@ -598,8 +588,7 @@ class StockFilter(rest_filters.FilterSet): """Filter stock items by "belongs_to" field being empty.""" if str2bool(value): return queryset.filter(installed_items__gt=0) - else: - return queryset.filter(installed_items=0) + return queryset.filter(installed_items=0) sent_to_customer = rest_filters.BooleanFilter(label='Sent to customer', method='filter_sent_to_customer') @@ -607,8 +596,7 @@ class StockFilter(rest_filters.FilterSet): """Filter by sent to customer.""" if str2bool(value): return queryset.exclude(customer=None) - else: - return queryset.filter(customer=None) + return queryset.filter(customer=None) depleted = rest_filters.BooleanFilter(label='Depleted', method='filter_depleted') @@ -616,8 +604,7 @@ class StockFilter(rest_filters.FilterSet): """Filter by depleted items.""" if str2bool(value): return queryset.filter(quantity__lte=0) - else: - return queryset.exclude(quantity__lte=0) + return queryset.exclude(quantity__lte=0) has_purchase_price = rest_filters.BooleanFilter(label='Has purchase price', method='filter_has_purchase_price') @@ -625,8 +612,7 @@ class StockFilter(rest_filters.FilterSet): """Filter by having a purchase price.""" if str2bool(value): return queryset.exclude(purchase_price=None) - else: - return queryset.filter(purchase_price=None) + return queryset.filter(purchase_price=None) ancestor = rest_filters.ModelChoiceFilter( label='Ancestor', @@ -896,8 +882,7 @@ class StockList(APIDownloadMixin, ListCreateDestroyAPIView): return self.get_paginated_response(data) elif request.is_ajax(): return JsonResponse(data, safe=False) - else: - return Response(data) + return Response(data) def get_queryset(self, *args, **kwargs): """Annotate queryset before returning.""" @@ -1359,8 +1344,7 @@ class StockTrackingList(ListAPI): return self.get_paginated_response(data) if request.is_ajax(): return JsonResponse(data, safe=False) - else: - return Response(data) + return Response(data) def create(self, request, *args, **kwargs): """Create a new StockItemTracking object. diff --git a/InvenTree/stock/models.py b/InvenTree/stock/models.py index 9bf0d69778..f6eb6b876e 100644 --- a/InvenTree/stock/models.py +++ b/InvenTree/stock/models.py @@ -1842,9 +1842,8 @@ class StockItem(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, commo self.delete() return False - else: - self.save() - return True + self.save() + return True @transaction.atomic def stocktake(self, count, user, notes=''): @@ -2234,8 +2233,7 @@ class StockItemTracking(models.Model): """Return label.""" if self.tracking_type in StockHistoryCode.keys(): return StockHistoryCode.label(self.tracking_type) - else: - return self.title + return self.title tracking_type = models.IntegerField( default=StockHistoryCode.LEGACY, diff --git a/InvenTree/users/models.py b/InvenTree/users/models.py index 0d2f94448a..89f619d635 100644 --- a/InvenTree/users/models.py +++ b/InvenTree/users/models.py @@ -308,8 +308,7 @@ class RuleSet(models.Model): return f'{str(self.group).ljust(15)}: {self.name.title().ljust(15)} | ' \ f'v: {str(self.can_view).ljust(5)} | a: {str(self.can_add).ljust(5)} | ' \ f'c: {str(self.can_change).ljust(5)} | d: {str(self.can_delete).ljust(5)}' - else: - return self.name + return self.name def save(self, *args, **kwargs): """Intercept the 'save' functionality to make additional permission changes: