Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Drop type ignore anotations where it is possible

IKarbowiak4de8ac94188e
diff --git a/saleor/core/payments.py b/saleor/core/payments.py
index 55e563a69a..e197a9cef7 100644
--- a/saleor/core/payments.py
+++ b/saleor/core/payments.py
@@ -13,7 +13,7 @@ if TYPE_CHECKING:
class PaymentInterface(ABC):
@abstractmethod
- def list_payment_gateways(self, active_only: bool) -> List[str]:
+ def list_payment_gateways(self, active_only: bool) -> List[dict]:
pass
@abstractmethod
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index df3099dacb..b43e001725 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -74,7 +74,7 @@ def get_product_discount_on_sale(
def get_product_discounts(product: "Product", discounts: "DiscountsListType") -> Money:
"""Return discount values for all discounts applicable to a product."""
product_collections = set(product.collections.all().values_list("pk", flat=True))
- for discount in discounts: # type: ignore
+ for discount in discounts or []:
try:
yield get_product_discount_on_sale(product, product_collections, discount)
except NotApplicable:
diff --git a/saleor/extensions/manager.py b/saleor/extensions/manager.py
index cbf75c38ab..3cb452e03c 100644
--- a/saleor/extensions/manager.py
+++ b/saleor/extensions/manager.py
@@ -294,7 +294,7 @@ class ExtensionsManager(PaymentInterface):
if payment_method in type(plugin).__dict__
]
- def list_payment_gateways(self, active_only: bool = True) -> List[dict]: # type: ignore
+ def list_payment_gateways(self, active_only: bool = True) -> List[dict]:
payment_plugins = self.list_payment_plugin_names(active_only=active_only)
return [
{"name": plugin_name, "config": self.__get_payment_config(plugin_name)}
diff --git a/saleor/extensions/plugins/anonymize/plugin.py b/saleor/extensions/plugins/anonymize/plugin.py
index 2bb6939d86..d7632bcdec 100644
--- a/saleor/extensions/plugins/anonymize/plugin.py
+++ b/saleor/extensions/plugins/anonymize/plugin.py
@@ -25,7 +25,7 @@ class AnonymizePlugin(BasePlugin):
previous_value: "Address",
) -> "Address":
if address.phone:
- address.phone = "" # type: ignore
+ address.phone = address.phone.default
address = obfuscate_address(address)
address.save()
return address
diff --git a/saleor/extensions/plugins/avatax/plugin.py b/saleor/extensions/plugins/avatax/plugin.py
index e27622eaea..64546314d1 100644
--- a/saleor/extensions/plugins/avatax/plugin.py
+++ b/saleor/extensions/plugins/avatax/plugin.py
@@ -369,7 +369,7 @@ class AvataxPlugin(BasePlugin):
net = Money(amount=net, currency=currency)
return TaxedMoney(net=net, gross=gross)
return TaxedMoney(
- # Ignore mypy checking because it is checked in _validate_order
+ # Ignore typing checks because it is checked in _validate_order
net=order.shipping_method.price, # type: ignore
gross=order.shipping_method.price, # type: ignore
)
diff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.py
index 46eee79a61..a9c65dc5f0 100644
--- a/saleor/graphql/menu/mutations.py
+++ b/saleor/graphql/menu/mutations.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from dataclasses import dataclass
-from typing import Dict, List, Optional
+from typing import Dict, List, Optional, Type
import graphene
from django.core.exceptions import ValidationError
@@ -150,12 +150,12 @@ class MenuDelete(ModelDeleteMutation):
def _validate_menu_item_instance(
- cleaned_input: dict, field: str, expected_model: Model
+ cleaned_input: dict, field: str, expected_model: Type[Model]
):
"""Check if the value to assign as a menu item matches the expected model."""
item = cleaned_input.get(field)
if item:
- if not isinstance(item, expected_model): # type: ignore
+ if not isinstance(item, expected_model):
msg = (
f"Enter a valid {expected_model._meta.verbose_name} ID "
f"(got {item._meta.verbose_name} ID)."
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 6565b8fbd1..8610e3eb46 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -1,7 +1,7 @@
import json
import logging
import traceback
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple, Union
from django.conf import settings
from django.http import HttpRequest, HttpResponseNotAllowed, JsonResponse
@@ -92,13 +92,17 @@ class GraphQLView(View):
if isinstance(data, list):
responses = [self.get_response(request, entry) for entry in data]
- result = [response for response, code in responses]
+ result: Union[list, Optional[dict]] = [
+ response for response, code in responses
+ ]
status_code = max((code for response, code in responses), default=200)
else:
result, status_code = self.get_response(request, data)
return JsonResponse(data=result, status=status_code, safe=False)
- def get_response(self, request: HttpRequest, data: dict):
+ def get_response(
+ self, request: HttpRequest, data: dict
+ ) -> Tuple[Optional[Dict[str, List[Any]]], int]:
execution_result = self.execute_graphql_request(request, data)
status_code = 200
if execution_result:
@@ -111,9 +115,9 @@ class GraphQLView(View):
status_code = 400
else:
response["data"] = execution_result.data
- result = response
+ result: Optional[Dict[str, List[Any]]] = response
else:
- result = None # type: ignore
+ result = None
return result, status_code
def get_root_value(self):
@@ -139,7 +143,9 @@ class GraphQLView(View):
# Attempt to parse the query, if it fails, return the error
try:
return (
- self.backend.document_from_string(self.schema, query), # type: ignore
+ self.backend.document_from_string( # type: ignore
+ self.schema, query
+ ),
None,
)
except (ValueError, GraphQLSyntaxError) as e:
diff --git a/saleor/graphql/wishlist/resolvers.py b/saleor/graphql/wishlist/resolvers.py
index a13f5723e8..c9377c9785 100644
--- a/saleor/graphql/wishlist/resolvers.py
+++ b/saleor/graphql/wishlist/resolvers.py
@@ -12,8 +12,8 @@ if TYPE_CHECKING:
def resolve_wishlist_from_user(user: "User") -> Wishlist:
"""Return wishlist of the logged in user."""
- wishlist = Wishlist.objects.get_or_create(user=user)
- return wishlist # type: ignore
+ wishlist, _ = Wishlist.objects.get_or_create(user=user)
+ return wishlist
def resolve_wishlist_from_info(info: "ResolveInfo") -> Wishlist:
diff --git a/saleor/order/events.py b/saleor/order/events.py
index d390553038..832e9acf6a 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -37,9 +37,9 @@ def email_sent_event(
) -> OrderEvent:
if user and not user.is_anonymous:
- kwargs = {"user": user}
+ kwargs: Dict[str, Union[User, int]] = {"user": user}
elif user_pk:
- kwargs = {"user_id": user_pk} # type: ignore
+ kwargs = {"user_id": user_pk}
else:
kwargs = {}
@@ -96,10 +96,11 @@ def order_created_event(
event_type = OrderEvents.PLACED
account_events.customer_placed_order_event(user=user, order=order)
- if user.is_anonymous:
- user = None # type: ignore
+ order_event_user = None if user.is_anonymous else user
- return OrderEvent.objects.create(order=order, type=event_type, user=user)
+ return OrderEvent.objects.create(
+ order=order, type=event_type, user=order_event_user
+ )
def draft_order_oversold_items_event(
diff --git a/saleor/product/models.py b/saleor/product/models.py
index cd2c18a759..1d15448e05 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -42,9 +42,11 @@ from ..seo.models import SeoModel, SeoModelTranslation
from . import AttributeInputType
if TYPE_CHECKING:
+ # flake8: noqa
from prices import Money
from ..account.models import User
+ from django.db.models import OrderBy
class Category(MPTTModel, ModelWithMetadata, SeoModel):
@@ -220,27 +222,23 @@ class ProductsQueryset(PublishedQuerySet):
),
output_field=models.CharField(),
),
+ concatenated_values_order=Case(
+ # Make the products having no such attribute be last in the sorting
+ When(concatenated_values=None, then=2),
+ # Put the products having an empty attribute value at the bottom of
+ # the other products.
+ When(concatenated_values="", then=1),
+ # Put the products having an attribute value to be always at the top
+ default=0,
+ output_field=models.IntegerField(),
+ ),
)
- qs = qs.extra(
- order_by=[
- Case( # type: ignore
- # Make the products having no such attribute be last in the sorting
- When(concatenated_values=None, then=2),
- # Put the products having an empty attribute value at the bottom of
- # the other products.
- When(concatenated_values="", then=1),
- # Put the products having an attribute value to be always at the top
- default=0,
- output_field=models.IntegerField(),
- ),
- # Sort each group of products (0, 1, 2, ...) per attribute values
- "concatenated_values",
- # Sort each group of products by name,
- # if they have the same values or not values
- "name",
- ]
- )
+ # Sort by concatenated_values_order then
+ # Sort each group of products (0, 1, 2, ...) per attribute values
+ # Sort each group of products by name,
+ # if they have the same values or not values
+ qs = qs.order_by("concatenated_values_order", "concatenated_values", "name")
# Descending sorting
if not ascending:
@@ -741,10 +739,10 @@ class AttributeQuerySet(BaseAttributeQuerySet):
id_field = F(f"{m2m_field_name}__id")
if asc:
sort_method = sort_order_field.asc(nulls_last=True)
- id_sort = id_field
+ id_sort: Union["OrderBy", "F"] = id_field
else:
sort_method = sort_order_field.desc(nulls_first=True)
- id_sort = id_field.desc() # type: ignore
+ id_sort = id_field.desc()
return self.order_by(sort_method, id_sort)
diff --git a/saleor/site/models.py b/saleor/site/models.py
index aaa4071478..cfef87093b 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -19,17 +19,18 @@ from .patch_sites import patch_contrib_sites
patch_contrib_sites()
-EMAIL_SENDER_NAME_VALIDATORS = [
- RegexValidator(
- r"[\n\r]",
- inverse_match=True,
- message=pgettext_lazy(
- "Email sender name validation error", "New lines are not allowed."
+def email_sender_name_validators():
+ return [
+ RegexValidator(
+ r"[\n\r]",
+ inverse_match=True,
+ message=pgettext_lazy(
+ "Email sender name validation error", "New lines are not allowed."
+ ),
+ code=SiteErrorCode.FORBIDDEN_CHARACTER.value,
),
- code=SiteErrorCode.FORBIDDEN_CHARACTER.value,
- ),
- MaxLengthValidator(settings.DEFAULT_MAX_EMAIL_DISPLAY_NAME_LENGTH),
-]
+ MaxLengthValidator(settings.DEFAULT_MAX_EMAIL_DISPLAY_NAME_LENGTH),
+ ]
class SiteSettings(models.Model):
@@ -66,7 +67,7 @@ class SiteSettings(models.Model):
max_length=settings.DEFAULT_MAX_EMAIL_DISPLAY_NAME_LENGTH,
blank=True,
default="",
- validators=EMAIL_SENDER_NAME_VALIDATORS, # type: ignore
+ validators=email_sender_name_validators(),
)
default_mail_sender_address = models.EmailField(blank=True, null=True)
customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)
diff --git a/saleor/wishlist/models.py b/saleor/wishlist/models.py
index b36f73c041..1b512113ab 100644
--- a/saleor/wishlist/models.py
+++ b/saleor/wishlist/models.py
@@ -6,15 +6,6 @@ from ..account.models import User
from ..product.models import Product, ProductVariant
-class WishlistQuerySet(models.QuerySet):
- def get_or_create(self, user: "User"): # type: ignore
- # pylint: disable=W0221
- try:
- return user.wishlist
- except self.model.DoesNotExist:
- return self.create(user=user)
-
-
class Wishlist(models.Model):
token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
user = models.OneToOneField(
@@ -22,8 +13,6 @@ class Wishlist(models.Model):
)
created_at = models.DateTimeField(auto_now_add=True)
- objects = WishlistQuerySet.as_manager()
-
def set_user(self, user):
self.user = user
self.save()