Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Enable PYI lint rules in Ruff
Patryk Zawadzkidea5ffb730ac
diff --git a/pyproject.toml b/pyproject.tomlindex ebad19fb3b..7121150b61 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -199,6 +199,7 @@ target-version = "py39""LOG","PIE","PT",+ "PYI","T20","UP","W"@@ -221,7 +222,8 @@ target-version = "py39""D213", # Multi-line docstring summary should start at the second line"D407", # Missing dashed underline after section"E501", # Line too long- "PT019" # Fixture without value is injected as parameter, use @pytest.mark.usefixtures instead+ "PT019", # Fixture without value is injected as parameter, use @pytest.mark.usefixtures instead+ "PYI041" # Use `float` instead of `int | float`][tool.ruff.lint.flake8-pytest-style]diff --git a/saleor/core/schedules.py b/saleor/core/schedules.pyindex 159ef7dc6f..674b943afc 100644--- a/saleor/core/schedules.py+++ b/saleor/core/schedules.py@@ -1,13 +1,15 @@import datetime-from collections import namedtuple-from typing import cast+from typing import NamedTuple, castfrom celery.utils.time import maybe_timedelta, remainingfrom django.db.models import F, Qfrom ..schedulers.customschedule import CustomSchedule-schedstate = namedtuple("schedstate", ("is_due", "next"))++class schedstate(NamedTuple):+ is_due: bool+ next: floatclass promotion_webhook_schedule(CustomSchedule):diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.pyindex 2bc0d80da4..a4ced6f84f 100644--- a/saleor/discount/utils/promotion.py+++ b/saleor/discount/utils/promotion.py@@ -1,9 +1,9 @@import datetime-from collections import defaultdict, namedtuple+from collections import defaultdictfrom collections.abc import Iterable, Iteratorfrom decimal import Decimalfrom itertools import chain-from typing import TYPE_CHECKING, Callable, Optional, Union, overload+from typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Union, overloadfrom uuid import UUIDimport graphene@@ -333,8 +333,8 @@ def get_discount_translated_name(rule_info: "VariantPromotionRuleInfo"):def _update_promotion_discount(- rule: "PromotionRule",- rule_info: "VariantPromotionRuleInfo",+ rule: PromotionRule,+ rule_info: VariantPromotionRuleInfo,rule_discount_amount: Decimal,discount_to_update: Union["CheckoutLineDiscount", "CheckoutDiscount", "OrderLineDiscount", "OrderDiscount"@@ -367,15 +367,17 @@ def _update_promotion_discount(def get_best_rule(- rules: Iterable["PromotionRule"],+ rules: Iterable[PromotionRule],channel: "Channel",country: str,subtotal: Money,database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):- RuleDiscount = namedtuple(- "RuleDiscount", ["rule", "discount_amount", "gift_listing"]- )+ class RuleDiscount(NamedTuple):+ rule: PromotionRule+ discount_amount: Money+ gift_listing: Optional[ProductVariantChannelListing]+currency_code = channel.currency_coderule_discounts: list[RuleDiscount] = []gift_rules = [rule for rule in rules if rule.reward_type == RewardType.GIFT]diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex a8b5f262a2..fea1f60b83 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -1,13 +1,13 @@import datetimeimport re-from collections import defaultdict, namedtuple+from collections import defaultdictfrom collections.abc import Iterablefrom dataclasses import dataclass-from typing import TYPE_CHECKING, Optional, Union+from typing import TYPE_CHECKING, NamedTuple, Optional, Unionimport graphenefrom django.core.exceptions import ValidationError-from django.db.models import Q+from django.db.models import Model, Qfrom django.db.models.expressions import Exists, OuterReffrom django.template.defaultfilters import truncatecharsfrom django.utils.text import slugify@@ -72,7 +72,11 @@ T_INSTANCE = Union[T_INPUT_MAP = list[tuple[attribute_models.Attribute, AttrValuesInput]]T_ERROR_DICT = dict[tuple[str, str], list]-EntityTypeData = namedtuple("EntityTypeData", ["model", "name_field", "value_field"])++class EntityTypeData(NamedTuple):+ model: type[Model]+ name_field: str+ value_field: strclass AttributeAssignmentMixin:@@ -226,7 +230,7 @@ class AttributeAssignmentMixin::raises ValidationError: contain the message.:return: The resolved data"""- error_class: Union[type[PageErrorCode], type[ProductErrorCode]] = (+ error_class: type[Union[PageErrorCode, ProductErrorCode]] = (PageErrorCode if is_page_attributes else ProductErrorCode)diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.pyindex 8677b9f35b..b3e255ff00 100644--- a/saleor/graphql/order/mutations/order_lines_create.py+++ b/saleor/graphql/order/mutations/order_lines_create.py@@ -1,4 +1,4 @@-from collections import defaultdict, namedtuple+from collections import defaultdictimport graphenefrom django.core.exceptions import ValidationError@@ -35,8 +35,6 @@ from .utils import (get_variant_rule_info_map,)-VariantData = namedtuple("VariantData", ["variant", "rules_info"])-class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):order = graphene.Field(Order, description="Related order.")diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.pyindex 963ad30e4e..e89f22bbf9 100644--- a/saleor/graphql/order/mutations/utils.py+++ b/saleor/graphql/order/mutations/utils.py@@ -1,5 +1,4 @@-from collections import namedtuple-from typing import Optional+from typing import NamedTuple, Optionalimport graphenefrom django.conf import settings@@ -7,7 +6,7 @@ from django.core.exceptions import ValidationErrorfrom ....checkout.fetch import get_variant_channel_listingfrom ....core.taxes import zero_money, zero_taxed_money-from ....discount.interface import fetch_variant_rules_info+from ....discount.interface import VariantPromotionRuleInfo, fetch_variant_rules_infofrom ....order import ORDER_EDITABLE_STATUS, OrderStatus, eventsfrom ....order.actions import call_order_eventfrom ....order.error_codes import OrderErrorCode@@ -190,7 +189,9 @@ def clean_payment(payment: Optional[payment_models.Payment]) -> payment_models.Preturn payment-VariantData = namedtuple("VariantData", ["variant", "rules_info"])+class VariantData(NamedTuple):+ variant: product_models.ProductVariant+ rules_info: list[VariantPromotionRuleInfo]def get_variant_rule_info_map(diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pyindex 82fde2574f..e39af6a57a 100644--- a/saleor/graphql/product/utils.py+++ b/saleor/graphql/product/utils.py@@ -1,6 +1,7 @@-from collections import defaultdict, namedtuple+from collections import defaultdictfrom collections.abc import Iterable-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, NamedTuple, Optional+from uuid import UUIDimport graphenefrom django.core.exceptions import ValidationError@@ -97,9 +98,10 @@ def create_stocks(return new_stocks-DraftOrderLinesData = namedtuple(- "DraftOrderLinesData", ["order_to_lines_mapping", "line_pks", "order_pks"]-)+class DraftOrderLinesData(NamedTuple):+ order_to_lines_mapping: dict+ line_pks: set[UUID]+ order_pks: set[UUID]def get_draft_order_lines_data_for_variants(diff --git a/saleor/order/tests/fixtures/fulfillment.py b/saleor/order/tests/fixtures/fulfillment.pyindex 39d5e6249d..c3c0d3bc5e 100644--- a/saleor/order/tests/fixtures/fulfillment.py+++ b/saleor/order/tests/fixtures/fulfillment.py@@ -1,9 +1,10 @@-from collections import namedtuple+from typing import NamedTupleimport grapheneimport pytest-from ...models import FulfillmentLine, FulfillmentStatus, OrderLine+from ....warehouse.models import Warehouse+from ...models import FulfillmentLine, FulfillmentStatus, Order, OrderLine@pytest.fixture@@ -36,7 +37,11 @@ def fulfillment_awaiting_approval(fulfilled_order):@pytest.fixturedef order_fulfill_data(order_with_lines, warehouse, checkout):- FulfillmentData = namedtuple("FulfillmentData", "order variables warehouse")+ class FulfillmentData(NamedTuple):+ order: Order+ variables: dict+ warehouse: Warehouse+order = order_with_linesorder_id = graphene.Node.to_global_id("Order", order.id)order_line, order_line2 = order.lines.all()diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pyindex 8ef3a1eb88..1d85484b9d 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -1,6 +1,6 @@import datetimeimport json-from collections import namedtuple+from typing import NamedTuplefrom unittest import mockimport pytest@@ -54,7 +54,11 @@ def payment_removed_app(payment_dummy):return payment_dummy-WebhookTestData = namedtuple("WebhookTestData", "secret, event_type, data, message")+class WebhookTestData(NamedTuple):+ secret: str+ event_type: WebhookEventAsyncType+ data: str+ message: bytes@pytest.fixturediff --git a/saleor/product/migrations/0183_calculate_discounted_prices.py b/saleor/product/migrations/0183_calculate_discounted_prices.pyindex 220e627988..598bcd7e54 100644--- a/saleor/product/migrations/0183_calculate_discounted_prices.py+++ b/saleor/product/migrations/0183_calculate_discounted_prices.py@@ -1,8 +1,9 @@# Generated by Django 3.2.18 on 2023-05-05 07:46-from collections import defaultdict, namedtuple+from collections import defaultdictfrom decimal import ROUND_HALF_UPfrom functools import partial+from typing import NamedTupleimport mpttimport mptt.managers@@ -13,17 +14,14 @@ from prices import Money, fixed_discount, percentage_discountBATCH_SIZE = 500-DiscountInfo = namedtuple(- "DiscountInfo",- [- "sale",- "channel_listings",- "product_ids",- "category_ids",- "collection_ids",- "variants_ids",- ],-)++class DiscountInfo(NamedTuple):+ sale: object+ channel_listings: dict+ product_ids: set[int]+ category_ids: set[int]+ collection_ids: set[int]+ variants_ids: set[int]def calculate_variants_discounted_price(apps, schema_editor):diff --git a/saleor/thumbnail/views.py b/saleor/thumbnail/views.pyindex 7e7079f999..fb2b792c88 100644--- a/saleor/thumbnail/views.py+++ b/saleor/thumbnail/views.py@@ -1,6 +1,5 @@import logging-from collections import namedtuple-from typing import Optional+from typing import NamedTuple, Optional, Unionfrom django.conf import settingsfrom django.core.exceptions import ObjectDoesNotExist@@ -29,7 +28,12 @@ from .utils import (logger = logging.getLogger(__name__)-ModelData = namedtuple("ModelData", ["model", "image_field", "thumbnail_field"])++class ModelData(NamedTuple):+ model: type[Union[App, AppInstallation, Category, Collection, ProductMedia, User]]+ image_field: str+ thumbnail_field: str+ICON_TYPE_TO_MODEL_DATA_MAPPING = {"App": ModelData(App, "brand_logo_default", "app"),@@ -93,11 +97,11 @@ def handle_thumbnail(try:if object_type in UUID_IDENTIFIABLE_TYPES:- instance = model_data.model.objects.using(+ instance = model_data.model.objects.using( # type: ignoresettings.DATABASE_CONNECTION_REPLICA_NAME).get(uuid=pk)else:- instance = model_data.model.objects.using(+ instance = model_data.model.objects.using( # type: ignoresettings.DATABASE_CONNECTION_REPLICA_NAME).get(id=pk)except ObjectDoesNotExist:diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex fbf0a27a63..62f3441b99 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -1,7 +1,7 @@import math-from collections import defaultdict, namedtuple+from collections import defaultdictfrom collections.abc import Iterable-from typing import TYPE_CHECKING, Any, Optional, cast+from typing import TYPE_CHECKING, Any, NamedTuple, Optional, castfrom uuid import UUIDfrom django.db import transaction@@ -38,7 +38,9 @@ if TYPE_CHECKING:from ..order.models import Order-StockData = namedtuple("StockData", ["pk", "quantity"])+class StockData(NamedTuple):+ pk: int+ quantity: int@traced_atomic_transaction()diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.pyindex 8937f86b5d..604c18dd6e 100644--- a/saleor/warehouse/reservations.py+++ b/saleor/warehouse/reservations.py@@ -1,7 +1,7 @@import datetime-from collections import defaultdict, namedtuple+from collections import defaultdictfrom collections.abc import Iterable-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, NamedTuple, Optionalfrom django.conf import settingsfrom django.db.models import F, Sum@@ -18,7 +18,10 @@ if TYPE_CHECKING:from ..channel.models import Channelfrom ..checkout.fetch import CheckoutLine-StockData = namedtuple("StockData", ["pk", "quantity"])++class StockData(NamedTuple):+ pk: int+ quantity: int@traced_atomic_transaction()