Skip to content

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

Enable pyupgrade rules in ruff

Patryk Zawadzki74c113873657
diff --git a/pyproject.toml b/pyproject.toml
index 8c2984c86a..cd0155e19a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -131,8 +131,8 @@ documentation = "https://docs.saleor.io/"
semgrep = ">=1.34.0"
[tool.ruff]
-extend-select = ["D", "I"]
-ignore = ["D100", "D101", "D102", "D103", "D104", "D105", "D106", "D107", "D202", "D203", "D213", "D407"]
+extend-select = ["D", "I", "UP"]
+ignore = ["D100", "D101", "D102", "D103", "D104", "D105", "D106", "D107", "D202", "D203", "D206", "D213", "D407"]
target-version = "py39"
[tool.ruff.isort]
diff --git a/saleor/__init__.py b/saleor/__init__.py
index 8e7726189c..abbe6a77ad 100644
--- a/saleor/__init__.py
+++ b/saleor/__init__.py
@@ -6,7 +6,7 @@ __all__ = ["celery_app"]
__version__ = "3.18.0-a.0"
-class PatchedSubscriberExecutionContext(object):
+class PatchedSubscriberExecutionContext:
__slots__ = "exe_context", "errors"
def __init__(self, exe_context):
diff --git a/saleor/account/forms.py b/saleor/account/forms.py
index ecb7706157..a01e7e87fb 100644
--- a/saleor/account/forms.py
+++ b/saleor/account/forms.py
@@ -13,7 +13,7 @@ def get_address_form(
if initial is None and country_code:
initial = {}
if country_code:
- initial["phone"] = "+{}".format(country_code_for_region(country_code))
+ initial["phone"] = f"+{country_code_for_region(country_code)}"
address_form_class = get_address_form_class(country_code)
if instance is not None:
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index a5324ad697..64bf72afb3 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List, Tuple
import i18naddress
from django import forms
@@ -139,7 +138,7 @@ class AddressForm(forms.ModelForm):
class CountryAwareAddressForm(AddressForm):
- I18N_MAPPING: List[Tuple[str, List[str]]] = [
+ I18N_MAPPING: list[tuple[str, list[str]]] = [
("name", ["first_name", "last_name"]),
("street_address", ["street_address_1", "street_address_2"]),
("city_area", ["city_area"]),
@@ -255,7 +254,7 @@ def construct_address_form(country_code, i18n_rules):
class_name = f"AddressForm{country_code}"
base_class = CountryAwareAddressForm
form_kwargs = {
- "Meta": type(str("Meta"), (base_class.Meta, object), {}),
+ "Meta": type("Meta", (base_class.Meta, object), {}),
"formfield_callback": None,
"i18n_country_code": country_code,
"i18n_fields_order": property(get_form_i18n_lines),
diff --git a/saleor/account/management/commands/createsuperuser.py b/saleor/account/management/commands/createsuperuser.py
index a3ec45b4c2..20789dd0df 100644
--- a/saleor/account/management/commands/createsuperuser.py
+++ b/saleor/account/management/commands/createsuperuser.py
@@ -255,19 +255,17 @@ class Command(BaseCommand):
return val
def _get_input_message(self, field, default=None):
- return "%s%s%s: " % (
- capfirst(field.verbose_name),
- " (leave blank to use '%s')" % default if default else "",
- " (%s.%s)"
- % (
- field.remote_field.model._meta.object_name,
+ message = capfirst(field.verbose_name)
+ if default:
+ message += f" (leave blank to use '{default}')"
+ if field.remote_field:
+ field_name = (
field.m2m_target_field_name()
if field.many_to_many
- else field.remote_field.field_name,
+ else field.remote_field.field_name
)
- if field.remote_field
- else "",
- )
+ message += f" ({field.remote_field.model._meta.object_name}.{field_name})"
+ return message
def _validate_username(self, username, verbose_field_name, database):
"""Validate username. If invalid, return a string error message."""
diff --git a/saleor/account/migrations/0001_initial.py b/saleor/account/migrations/0001_initial.py
index 0829543bad..821d8b4c3e 100644
--- a/saleor/account/migrations/0001_initial.py
+++ b/saleor/account/migrations/0001_initial.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
diff --git a/saleor/account/migrations/0002_auto_20150907_0602.py b/saleor/account/migrations/0002_auto_20150907_0602.py
index c21520d566..9bf44e8f70 100644
--- a/saleor/account/migrations/0002_auto_20150907_0602.py
+++ b/saleor/account/migrations/0002_auto_20150907_0602.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/account/migrations/0003_auto_20151104_1102.py b/saleor/account/migrations/0003_auto_20151104_1102.py
index 9f01bd0683..09ffec55c8 100644
--- a/saleor/account/migrations/0003_auto_20151104_1102.py
+++ b/saleor/account/migrations/0003_auto_20151104_1102.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/account/migrations/0004_auto_20160114_0419.py b/saleor/account/migrations/0004_auto_20160114_0419.py
index 30fcc28d86..414428a89c 100644
--- a/saleor/account/migrations/0004_auto_20160114_0419.py
+++ b/saleor/account/migrations/0004_auto_20160114_0419.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-01-14 10:19
-from __future__ import unicode_literals
import django_countries.fields
from django.db import migrations
diff --git a/saleor/account/migrations/0005_auto_20160205_0651.py b/saleor/account/migrations/0005_auto_20160205_0651.py
index 95302451bb..c32d76284e 100644
--- a/saleor/account/migrations/0005_auto_20160205_0651.py
+++ b/saleor/account/migrations/0005_auto_20160205_0651.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.2 on 2016-02-05 12:51
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/account/migrations/0006_auto_20160829_0819.py b/saleor/account/migrations/0006_auto_20160829_0819.py
index b0721be647..7ec41c8ce6 100644
--- a/saleor/account/migrations/0006_auto_20160829_0819.py
+++ b/saleor/account/migrations/0006_auto_20160829_0819.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10 on 2016-08-29 13:19
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/account/migrations/0007_auto_20161115_0940.py b/saleor/account/migrations/0007_auto_20161115_0940.py
index 89555401d2..db502650b1 100644
--- a/saleor/account/migrations/0007_auto_20161115_0940.py
+++ b/saleor/account/migrations/0007_auto_20161115_0940.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.1 on 2016-11-15 15:40
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/account/migrations/0008_auto_20161115_1011.py b/saleor/account/migrations/0008_auto_20161115_1011.py
index 5c0864d89a..094fcce94c 100644
--- a/saleor/account/migrations/0008_auto_20161115_1011.py
+++ b/saleor/account/migrations/0008_auto_20161115_1011.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.1 on 2016-11-15 16:11
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/account/migrations/0009_auto_20170206_0407.py b/saleor/account/migrations/0009_auto_20170206_0407.py
index 2c2901803e..b8cb1fbd9c 100644
--- a/saleor/account/migrations/0009_auto_20170206_0407.py
+++ b/saleor/account/migrations/0009_auto_20170206_0407.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-06 10:07
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/account/migrations/0010_auto_20170919_0839.py b/saleor/account/migrations/0010_auto_20170919_0839.py
index bcd46ad159..e11c549a81 100644
--- a/saleor/account/migrations/0010_auto_20170919_0839.py
+++ b/saleor/account/migrations/0010_auto_20170919_0839.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-19 13:39
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/account/migrations/0011_auto_20171110_0552.py b/saleor/account/migrations/0011_auto_20171110_0552.py
index 54b63d32d3..9f407842e0 100644
--- a/saleor/account/migrations/0011_auto_20171110_0552.py
+++ b/saleor/account/migrations/0011_auto_20171110_0552.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-10 11:52
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/account/migrations/0012_auto_20171117_0846.py b/saleor/account/migrations/0012_auto_20171117_0846.py
index 092bbb7020..50a3e61a5d 100644
--- a/saleor/account/migrations/0012_auto_20171117_0846.py
+++ b/saleor/account/migrations/0012_auto_20171117_0846.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-17 14:46
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/account/migrations/0013_auto_20171120_0521.py b/saleor/account/migrations/0013_auto_20171120_0521.py
index bd18b5f490..9798af213a 100644
--- a/saleor/account/migrations/0013_auto_20171120_0521.py
+++ b/saleor/account/migrations/0013_auto_20171120_0521.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-20 11:21
-from __future__ import unicode_literals
import phonenumber_field.modelfields
import phonenumbers
diff --git a/saleor/account/migrations/0014_auto_20171129_1004.py b/saleor/account/migrations/0014_auto_20171129_1004.py
index 530345e88d..4cd3f681a5 100644
--- a/saleor/account/migrations/0014_auto_20171129_1004.py
+++ b/saleor/account/migrations/0014_auto_20171129_1004.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-29 16:04
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/account/migrations/0015_auto_20171213_0734.py b/saleor/account/migrations/0015_auto_20171213_0734.py
index eb44328f53..1013db5121 100644
--- a/saleor/account/migrations/0015_auto_20171213_0734.py
+++ b/saleor/account/migrations/0015_auto_20171213_0734.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-12-13 13:34
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/account/migrations/0016_auto_20180108_0814.py b/saleor/account/migrations/0016_auto_20180108_0814.py
index 331f809d0a..c6c324318e 100644
--- a/saleor/account/migrations/0016_auto_20180108_0814.py
+++ b/saleor/account/migrations/0016_auto_20180108_0814.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-08 14:14
-from __future__ import unicode_literals
import django.db.models.deletion
import django.utils.timezone
diff --git a/saleor/account/models.py b/saleor/account/models.py
index d93bd26432..df7eabf68f 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from functools import partial
-from typing import Iterable, Union
+from typing import Union
from uuid import uuid4
from django.conf import settings
diff --git a/saleor/account/search.py b/saleor/account/search.py
index 6213328591..4599ffa2c3 100644
--- a/saleor/account/search.py
+++ b/saleor/account/search.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from django.db.models import Q, Value, prefetch_related_objects
@@ -64,7 +64,7 @@ def generate_address_search_document_value(address: "Address"):
def generate_address_search_vector_value(
address: "Address", weight: str = "A"
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
search_vectors = [
NoValidationSearchVector(
Value(address.first_name),
diff --git a/saleor/account/tests/test_utils.py b/saleor/account/tests/test_utils.py
index 102bc068ff..5f7d81bbaf 100644
--- a/saleor/account/tests/test_utils.py
+++ b/saleor/account/tests/test_utils.py
@@ -1,4 +1,3 @@
-from typing import List
from unittest.mock import patch
import pytest
@@ -210,7 +209,7 @@ def users_with_similar_emails():
)
def test_email_case_sensitivity(email, expected_user, users_with_similar_emails):
# given
- users: List[User] = users_with_similar_emails
+ users: list[User] = users_with_similar_emails
# when
user = retrieve_user_by_email(email=email)
# then
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index 87496f877f..d4c07b5977 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -96,9 +96,9 @@ def create_superuser(credentials):
if created:
user.set_password(credentials["password"])
user.save()
- msg = "Superuser - %(email)s/%(password)s" % credentials
+ msg = f"Superuser - {credentials['email']}/{credentials['password']}"
else:
- msg = "Superuser already exists - %(email)s" % credentials
+ msg = f"Superuser already exists - {credentials['email']}"
return msg
diff --git a/saleor/account/widgets.py b/saleor/account/widgets.py
index 8f3dbf2777..cbb1154a5a 100644
--- a/saleor/account/widgets.py
+++ b/saleor/account/widgets.py
@@ -5,10 +5,10 @@ class DatalistTextWidget(Select):
input_type = "text"
def get_context(self, *args):
- context = super(DatalistTextWidget, self).get_context(*args)
+ context = super().get_context(*args)
context["widget"]["type"] = self.input_type
return context
def format_value(self, value):
- value = super(DatalistTextWidget, self).format_value(value)
+ value = super().format_value(value)
return value[0]
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index 5607c06d37..9de9b79728 100644
--- a/saleor/app/management/commands/create_app.py
+++ b/saleor/app/management/commands/create_app.py
@@ -1,5 +1,5 @@
import json
-from typing import Any, Dict, Optional
+from typing import Any, Optional
from django.core.management import BaseCommand, CommandError
from django.core.management.base import CommandParser
@@ -41,7 +41,7 @@ class Command(BaseCommand):
"argument is provided.",
)
- def send_app_data(self, target_url, data: Dict[str, Any]):
+ def send_app_data(self, target_url, data: dict[str, Any]):
domain = get_domain()
headers = {
# X- headers will be deprecated in Saleor 4.0, proper headers are without X-
diff --git a/saleor/app/management/commands/utils.py b/saleor/app/management/commands/utils.py
index 9c157c49ab..9d5af6e849 100644
--- a/saleor/app/management/commands/utils.py
+++ b/saleor/app/management/commands/utils.py
@@ -1,11 +1,9 @@
-from typing import List
-
from django.core.management import CommandError
from ....permission.enums import get_permissions, get_permissions_enum_list
-def clean_permissions(required_permissions: List[str]):
+def clean_permissions(required_permissions: list[str]):
all_permissions = {perm[0]: perm[1] for perm in get_permissions_enum_list()}
for perm in required_permissions:
if not all_permissions.get(perm):
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index c77f994248..16b8a46fa7 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -1,6 +1,7 @@
import logging
from collections import defaultdict
-from typing import Dict, Iterable, List, Optional
+from collections.abc import Iterable
+from typing import Optional
from django.core.exceptions import ValidationError
from django.db.models import Value
@@ -25,7 +26,7 @@ from .validators import AppURLValidator, brand_validator
logger = logging.getLogger(__name__)
-T_ERRORS = Dict[str, List[ValidationError]]
+T_ERRORS = dict[str, list[ValidationError]]
class RequiredSaleorVersionSpec(NpmSpec):
@@ -88,8 +89,8 @@ def clean_manifest_url(manifest_url):
def clean_permissions(
- required_permissions: List[str], saleor_permissions: Iterable[Permission]
-) -> List[Permission]:
+ required_permissions: list[str], saleor_permissions: Iterable[Permission]
+) -> list[Permission]:
missing_permissions = []
all_permissions = {perm[0]: perm[1] for perm in get_permissions_enum_list()}
for perm in required_permissions:
@@ -338,7 +339,7 @@ def clean_required_saleor_version(
required_version,
raise_for_saleor_version: bool,
saleor_version=__version__,
-) -> Optional[Dict]:
+) -> Optional[dict]:
if not required_version:
return None
try:
diff --git a/saleor/app/migrations/0023_populate_app_and_app_installation_uuid.py b/saleor/app/migrations/0023_populate_app_and_app_installation_uuid.py
index 4b5e6171a5..325aa5737d 100644
--- a/saleor/app/migrations/0023_populate_app_and_app_installation_uuid.py
+++ b/saleor/app/migrations/0023_populate_app_and_app_installation_uuid.py
@@ -13,8 +13,7 @@ def queryset_in_batches(qs, batch_size: int):
yield ids[index : min(index + batch_size, length)]
ids = qs.values_list("id", flat=True)
- for ids_batch in batch_ids():
- yield ids_batch
+ yield from batch_ids()
def update_uuid_field(model_cls, batch_size: int):
diff --git a/saleor/app/models.py b/saleor/app/models.py
index c58820e907..a034e1bc13 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -1,4 +1,5 @@
-from typing import Iterable, Set, Tuple, Union
+from collections.abc import Iterable
+from typing import Union
from uuid import uuid4
from django.contrib.auth.hashers import make_password
@@ -83,7 +84,7 @@ class App(ModelWithMetadata):
def __str__(self):
return self.name
- def get_permissions(self) -> Set[str]:
+ def get_permissions(self) -> set[str]:
"""Return the permissions of the app."""
if not self.is_active:
return set()
@@ -126,7 +127,7 @@ class AppTokenManager(models.Manager["AppToken"]):
app_token.save()
return app_token, auth_token
- def create_with_token(self, *args, **kwargs) -> Tuple["AppToken", str]:
+ def create_with_token(self, *args, **kwargs) -> tuple["AppToken", str]:
# As `create` is waiting to be fixed, I'm using this proper method from future
# to get both AppToken and auth_token.
return self.create(*args, **kwargs)
diff --git a/saleor/asgi/cors_handler.py b/saleor/asgi/cors_handler.py
index c6b07bf9db..571cf5e55c 100644
--- a/saleor/asgi/cors_handler.py
+++ b/saleor/asgi/cors_handler.py
@@ -1,5 +1,5 @@
from fnmatch import fnmatchcase
-from typing import Tuple, cast
+from typing import cast
from asgiref.typing import (
ASGI3Application,
@@ -36,7 +36,7 @@ def cors_handler(application: ASGI3Application) -> ASGI3Application:
break
if scope["method"] == "OPTIONS":
scope = cast(HTTPScope, scope)
- response_headers: list[Tuple[bytes, bytes]] = [
+ response_headers: list[tuple[bytes, bytes]] = [
(b"access-control-allow-credentials", b"true"),
(
b"access-control-allow-headers",
diff --git a/saleor/asgi/tests/test_cors.py b/saleor/asgi/tests/test_cors.py
index 9898c26c20..b04437b1a9 100644
--- a/saleor/asgi/tests/test_cors.py
+++ b/saleor/asgi/tests/test_cors.py
@@ -1,5 +1,3 @@
-from typing import List
-
import pytest
from asgiref.typing import (
ASGI3Application,
@@ -38,7 +36,7 @@ def build_scope(origin: str, method: str) -> HTTPScope:
}
-async def run_app(app: ASGI3Application, scope: HTTPScope) -> List[dict]:
+async def run_app(app: ASGI3Application, scope: HTTPScope) -> list[dict]:
events = []
async def send(event) -> None:
diff --git a/saleor/asgi/tests/test_gzip.py b/saleor/asgi/tests/test_gzip.py
index d7a764358c..01dfd9542a 100644
--- a/saleor/asgi/tests/test_gzip.py
+++ b/saleor/asgi/tests/test_gzip.py
@@ -1,5 +1,4 @@
import gzip
-from typing import List
from asgiref.typing import (
ASGI3Application,
@@ -34,7 +33,7 @@ def build_scope(origin: str, encodings: bytes) -> HTTPScope:
}
-async def run_app(app: ASGI3Application, scope: HTTPScope) -> List[dict]:
+async def run_app(app: ASGI3Application, scope: HTTPScope) -> list[dict]:
events = []
async def send(event) -> None:
diff --git a/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
index 33b5b6ef7e..6f4c200d42 100644
--- a/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
+++ b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
@@ -2,7 +2,7 @@
import re
import warnings
-from typing import Dict, Optional
+from typing import Optional
from django.db import migrations
from django.template.defaultfilters import truncatechars
@@ -14,7 +14,7 @@ BLACKLISTED_URL_SCHEMES = ("javascript",)
HYPERLINK_TAG_WITH_URL_PATTERN = r"(.*?<a\s+href=\\?\")(\w+://\S+[^\\])(\\?\">)"
-def clean_editor_js(definitions: Optional[Dict], *, to_string: bool = False):
+def clean_editor_js(definitions: Optional[dict], *, to_string: bool = False):
"""Sanitize a given EditorJS JSON definitions.
Look for not allowed URLs, replaced them with `invalid` value, and clean valid ones.
diff --git a/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
index 8c78deb8fe..9424129446 100644
--- a/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
+++ b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
@@ -2,7 +2,7 @@
import re
import warnings
-from typing import Dict, Optional
+from typing import Optional
from django.db import migrations
from django.template.defaultfilters import truncatechars
@@ -14,7 +14,7 @@ BLACKLISTED_URL_SCHEMES = ("javascript",)
HYPERLINK_TAG_WITH_URL_PATTERN = r"(.*?<a\s+href=\\?\")(\w+://\S+[^\\])(\\?\">)"
-def clean_editor_js(definitions: Optional[Dict], *, to_string: bool = False):
+def clean_editor_js(definitions: Optional[dict], *, to_string: bool = False):
"""Sanitize a given EditorJS JSON definitions.
Look for not allowed URLs, replaced them with `invalid` value, and clean valid ones.
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 246fc6f01e..12b49dd7a8 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -196,12 +196,7 @@ class AttributeTranslation(Translation):
def __repr__(self):
class_ = type(self)
- return "%s(pk=%r, name=%r, attribute_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.attribute_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, name={self.name!r}, attribute_pk={self.attribute_id!r})"
def __str__(self) -> str:
return self.name
@@ -290,12 +285,7 @@ class AttributeValueTranslation(Translation):
def __repr__(self) -> str:
class_ = type(self)
- return "%s(pk=%r, name=%r, attribute_value_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.attribute_value_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, name={self.name!r}, attribute_value_pk={self.attribute_value_id!r})"
def __str__(self) -> str:
return self.name
diff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.py
index 6a03bdf479..d8a07eef38 100644
--- a/saleor/attribute/utils.py
+++ b/saleor/attribute/utils.py
@@ -1,4 +1,5 @@
-from typing import TYPE_CHECKING, Iterable, Set, Union
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Union
from ..page.models import Page
from ..product.models import Product, ProductVariant
@@ -63,7 +64,7 @@ def associate_attribute_values_to_instance(
return assignment
-def validate_attribute_owns_values(attribute: Attribute, value_ids: Set[int]) -> None:
+def validate_attribute_owns_values(attribute: Attribute, value_ids: set[int]) -> None:
"""Check given value IDs are belonging to the given attribute.
:raise: AssertionError
diff --git a/saleor/auth/migrations/0011_update_proxy_permissions.py b/saleor/auth/migrations/0011_update_proxy_permissions.py
index 2b1ccecfcd..35a086573c 100644
--- a/saleor/auth/migrations/0011_update_proxy_permissions.py
+++ b/saleor/auth/migrations/0011_update_proxy_permissions.py
@@ -25,7 +25,7 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): # noqa:
if not opts.proxy:
continue
proxy_default_permissions_codenames = [
- "%s_%s" % (action, opts.model_name) for action in opts.default_permissions
+ f"{action}_{opts.model_name}" for action in opts.default_permissions
]
permissions_query = Q(codename__in=proxy_default_permissions_codenames)
for codename, name in opts.permissions:
@@ -46,8 +46,8 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): # noqa:
content_type=old_content_type,
).update(content_type=new_content_type)
except IntegrityError:
- old = "{}_{}".format(old_content_type.app_label, old_content_type.model)
- new = "{}_{}".format(new_content_type.app_label, new_content_type.model)
+ old = f"{old_content_type.app_label}_{old_content_type.model}"
+ new = f"{new_content_type.app_label}_{new_content_type.model}"
sys.stdout.write(
style.WARNING(WARNING.format(old=old, new=new, query=permissions_query))
)
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 9f35185482..5ad2781b20 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -6,7 +6,8 @@ taxes (Money instead of TaxedMoney). If you don't need pre-taxed prices use func
from calculations.py.
"""
-from typing import TYPE_CHECKING, Iterable, Optional
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional
from prices import Money
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index a8cdadbef2..ca7131d2c5 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
from django.conf import settings
from django.utils import timezone
@@ -223,7 +224,7 @@ def _fetch_checkout_prices_if_expired(
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"] = None,
force_update: bool = False,
-) -> Tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:
+) -> tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:
"""Fetch checkout prices with taxes.
First calculate and apply all checkout prices with taxes separately,
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index e8dd4ce0a6..d9116f8ef1 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from datetime import date
-from typing import TYPE_CHECKING, Iterable, Optional, Type, Union
+from typing import TYPE_CHECKING, Optional, Union
import graphene
from django.core.exceptions import ValidationError
@@ -24,9 +25,9 @@ def clean_checkout_shipping(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
error_code: Union[
- Type[CheckoutErrorCode],
- Type[PaymentErrorCode],
- Type[OrderCreateFromCheckoutErrorCode],
+ type[CheckoutErrorCode],
+ type[PaymentErrorCode],
+ type[OrderCreateFromCheckoutErrorCode],
],
):
delivery_method_info = checkout_info.delivery_method_info
@@ -65,9 +66,9 @@ def clean_checkout_shipping(
def clean_billing_address(
checkout_info: "CheckoutInfo",
error_code: Union[
- Type[CheckoutErrorCode],
- Type[PaymentErrorCode],
- Type[OrderCreateFromCheckoutErrorCode],
+ type[CheckoutErrorCode],
+ type[PaymentErrorCode],
+ type[OrderCreateFromCheckoutErrorCode],
],
):
if not checkout_info.billing_address:
@@ -85,7 +86,7 @@ def clean_checkout_payment(
manager: PluginsManager,
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
- error_code: Type[CheckoutErrorCode],
+ error_code: type[CheckoutErrorCode],
last_payment: Optional[payment_models.Payment],
):
clean_billing_address(checkout_info, error_code)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index f148233a89..00597e3c97 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -1,13 +1,10 @@
+from collections.abc import Iterable
from datetime import timedelta
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
- Dict,
- Iterable,
- List,
Optional,
- Tuple,
Union,
cast,
)
@@ -135,7 +132,7 @@ def _process_shipping_data_for_order(
shipping_price: TaxedMoney,
manager: "PluginsManager",
lines: Iterable["CheckoutLineInfo"],
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
"""Fetch, process and return shipping data from checkout."""
delivery_method_info = checkout_info.delivery_method_info
shipping_address = delivery_method_info.shipping_address
@@ -154,7 +151,7 @@ def _process_shipping_data_for_order(
shipping_method = delivery_method_info.delivery_method
tax_class = getattr(shipping_method, "tax_class", None)
- result: Dict[str, Any] = {
+ result: dict[str, Any] = {
"shipping_address": shipping_address,
"base_shipping_price": base_shipping_price,
"shipping_price": shipping_price,
@@ -191,8 +188,8 @@ def _create_line_for_order(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
- products_translation: Dict[int, Optional[str]],
- variants_translation: Dict[int, Optional[str]],
+ products_translation: dict[int, Optional[str]],
+ variants_translation: dict[int, Optional[str]],
prices_entered_with_tax: bool,
) -> OrderLineInfo:
"""Create a line for the given order.
@@ -340,7 +337,7 @@ def _create_line_for_order(
def _create_order_line_discounts(
checkout_line_info: "CheckoutLineInfo", order_line: "OrderLine"
-) -> List["OrderLineDiscount"]:
+) -> list["OrderLineDiscount"]:
line_discounts = []
discounts = checkout_line_info.get_promotion_discounts()
for discount in discounts:
@@ -521,8 +518,8 @@ def _create_order(
app: Optional["App"],
manager: "PluginsManager",
site_settings: Optional["SiteSettings"] = None,
- metadata_list: Optional[List] = None,
- private_metadata_list: Optional[List] = None,
+ metadata_list: Optional[list] = None,
+ private_metadata_list: Optional[list] = None,
) -> Order:
"""Create an order from the checkout.
@@ -565,8 +562,8 @@ def _create_order(
_handle_checkout_discount(order, checkout)
- order_lines: List[OrderLine] = []
- order_line_discounts: List[OrderLineDiscount] = []
+ order_lines: list[OrderLine] = []
+ order_line_discounts: list[OrderLineDiscount] = []
for line_info in order_lines_info:
line = line_info.line
line.order_id = order.pk
@@ -836,7 +833,7 @@ def complete_checkout_pre_payment_part(
user,
site_settings=None,
redirect_url=None,
-) -> Tuple[Optional[Payment], Optional[str], dict]:
+) -> tuple[Optional[Payment], Optional[str], dict]:
"""Logic required to process checkout before payment.
Should be used with transaction_with_commit_on_errors, as there is a possibility
@@ -886,11 +883,11 @@ def complete_checkout_post_payment_part(
user,
app,
site_settings=None,
- metadata_list: Optional[List] = None,
- private_metadata_list: Optional[List] = None,
-) -> Tuple[Optional[Order], bool, dict]:
+ metadata_list: Optional[list] = None,
+ private_metadata_list: Optional[list] = None,
+) -> tuple[Optional[Order], bool, dict]:
action_required = False
- action_data: Dict[str, str] = {}
+ action_data: dict[str, str] = {}
if payment and txn:
if txn.customer_id and user:
@@ -975,11 +972,11 @@ def _increase_voucher_usage(checkout_info: "CheckoutInfo"):
def _create_order_lines_from_checkout_lines(
checkout_info: CheckoutInfo,
- lines: List[CheckoutLineInfo],
+ lines: list[CheckoutLineInfo],
manager: "PluginsManager",
order_pk: Union[str, UUID],
prices_entered_with_tax: bool,
-) -> List[OrderLineInfo]:
+) -> list[OrderLineInfo]:
order_lines_info = _create_lines_for_order(
manager,
checkout_info,
@@ -987,7 +984,7 @@ def _create_order_lines_from_checkout_lines(
prices_entered_with_tax,
)
order_lines = []
- order_line_discounts: List["OrderLineDiscount"] = []
+ order_line_discounts: list["OrderLineDiscount"] = []
for line_info in order_lines_info:
line = line_info.line
line.order_id = order_pk
@@ -1003,8 +1000,8 @@ def _create_order_lines_from_checkout_lines(
def _handle_allocations_of_order_lines(
checkout_info: CheckoutInfo,
- checkout_lines: List[CheckoutLineInfo],
- order_lines_info: List[OrderLineInfo],
+ checkout_lines: list[CheckoutLineInfo],
+ order_lines_info: list[OrderLineInfo],
manager: "PluginsManager",
reservation_enabled: bool,
):
@@ -1050,7 +1047,7 @@ def _handle_checkout_discount(order: "Order", checkout: "Checkout"):
def _post_create_order_actions(
order: "Order",
checkout_info: "CheckoutInfo",
- order_lines_info: List["OrderLineInfo"],
+ order_lines_info: list["OrderLineInfo"],
manager: "PluginsManager",
user: Optional[User],
app: Optional["App"],
@@ -1084,12 +1081,12 @@ def _post_create_order_actions(
def _create_order_from_checkout(
checkout_info: CheckoutInfo,
- checkout_lines_info: List[CheckoutLineInfo],
+ checkout_lines_info: list[CheckoutLineInfo],
manager: "PluginsManager",
user: Optional[User],
app: Optional["App"],
- metadata_list: Optional[List] = None,
- private_metadata_list: Optional[List] = None,
+ metadata_list: Optional[list] = None,
+ private_metadata_list: Optional[list] = None,
):
from ..order.utils import add_gift_cards_to_order
@@ -1255,8 +1252,8 @@ def create_order_from_checkout(
user: Optional["User"],
app: Optional["App"],
delete_checkout: bool = True,
- metadata_list: Optional[List] = None,
- private_metadata_list: Optional[List] = None,
+ metadata_list: Optional[list] = None,
+ private_metadata_list: Optional[list] = None,
) -> Order:
"""Crate order from checkout.
@@ -1338,15 +1335,15 @@ def complete_checkout(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
- payment_data: Dict[Any, Any],
+ payment_data: dict[Any, Any],
store_source: bool,
user: Optional["User"],
app: Optional["App"],
site_settings: Optional["SiteSettings"] = None,
redirect_url: Optional[str] = None,
- metadata_list: Optional[List] = None,
- private_metadata_list: Optional[List] = None,
-) -> Tuple[Optional[Order], bool, dict]:
+ metadata_list: Optional[list] = None,
+ private_metadata_list: Optional[list] = None,
+) -> tuple[Optional[Order], bool, dict]:
transactions = checkout_info.checkout.payment_transactions.all()
fetch_checkout_data(checkout_info, manager, lines)
@@ -1398,8 +1395,8 @@ def complete_checkout_with_transaction(
user: Optional["User"],
app: Optional["App"],
redirect_url: Optional[str] = None,
- metadata_list: Optional[List] = None,
- private_metadata_list: Optional[List] = None,
+ metadata_list: Optional[list] = None,
+ private_metadata_list: Optional[list] = None,
) -> Optional[Order]:
try:
_prepare_checkout_with_transactions(
@@ -1443,9 +1440,9 @@ def complete_checkout_with_payment(
app,
site_settings=None,
redirect_url=None,
- metadata_list: Optional[List] = None,
- private_metadata_list: Optional[List] = None,
-) -> Tuple[Optional[Order], bool, dict]:
+ metadata_list: Optional[list] = None,
+ private_metadata_list: Optional[list] = None,
+) -> tuple[Optional[Order], bool, dict]:
"""Logic required to finalize the checkout and convert it to order.
Should be used with transaction_with_commit_on_errors, as there is a possibility
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index f7c0d785b4..bf13e306f3 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -1,15 +1,12 @@
import itertools
+from collections.abc import Iterable
from dataclasses import dataclass
from functools import singledispatch
from typing import (
TYPE_CHECKING,
Any,
Callable,
- Dict,
- Iterable,
- List,
Optional,
- Tuple,
Union,
)
from uuid import UUID
@@ -51,14 +48,14 @@ class CheckoutLineInfo:
channel_listing: "ProductVariantChannelListing"
product: "Product"
product_type: "ProductType"
- collections: List["Collection"]
- discounts: List["CheckoutLineDiscount"]
- rules_info: List["VariantPromotionRuleInfo"]
+ collections: list["Collection"]
+ discounts: list["CheckoutLineDiscount"]
+ rules_info: list["VariantPromotionRuleInfo"]
channel: "Channel"
tax_class: Optional["TaxClass"] = None
voucher: Optional["Voucher"] = None
- def get_promotion_discounts(self) -> List["CheckoutLineDiscount"]:
+ def get_promotion_discounts(self) -> list["CheckoutLineDiscount"]:
return [
discount
for discount in self.discounts
@@ -74,19 +71,19 @@ class CheckoutInfo:
billing_address: Optional["Address"]
shipping_address: Optional["Address"]
delivery_method_info: "DeliveryMethodBase"
- all_shipping_methods: List["ShippingMethodData"]
+ all_shipping_methods: list["ShippingMethodData"]
tax_configuration: "TaxConfiguration"
- valid_pick_up_points: List["Warehouse"]
+ valid_pick_up_points: list["Warehouse"]
voucher: Optional["Voucher"] = None
@property
- def valid_shipping_methods(self) -> List["ShippingMethodData"]:
+ def valid_shipping_methods(self) -> list["ShippingMethodData"]:
return [method for method in self.all_shipping_methods if method.active]
@property
def valid_delivery_methods(
self,
- ) -> List[Union["ShippingMethodData", "Warehouse"]]:
+ ) -> list[Union["ShippingMethodData", "Warehouse"]]:
return list(
itertools.chain(
self.valid_shipping_methods,
@@ -123,10 +120,10 @@ class DeliveryMethodBase:
return False
@property
- def delivery_method_name(self) -> Dict[str, Optional[str]]:
+ def delivery_method_name(self) -> dict[str, Optional[str]]:
return {"shipping_method_name": None}
- def get_warehouse_filter_lookup(self) -> Dict[str, Any]:
+ def get_warehouse_filter_lookup(self) -> dict[str, Any]:
return {}
def is_valid_delivery_method(self) -> bool:
@@ -143,7 +140,7 @@ class ShippingMethodInfo(DeliveryMethodBase):
store_as_customer_address: bool = True
@property
- def delivery_method_name(self) -> Dict[str, Optional[str]]:
+ def delivery_method_name(self) -> dict[str, Optional[str]]:
return {"shipping_method_name": str(self.delivery_method.name)}
@property
@@ -183,10 +180,10 @@ class CollectionPointInfo(DeliveryMethodBase):
)
@property
- def delivery_method_name(self) -> Dict[str, Optional[str]]:
+ def delivery_method_name(self) -> dict[str, Optional[str]]:
return {"collection_point_name": str(self.delivery_method)}
- def get_warehouse_filter_lookup(self) -> Dict[str, Any]:
+ def get_warehouse_filter_lookup(self) -> dict[str, Any]:
return (
{"warehouse_id": self.delivery_method.pk}
if self.is_local_collection_point
@@ -229,7 +226,7 @@ def fetch_checkout_lines(
skip_lines_with_unavailable_variants: bool = True,
skip_recalculation: bool = False,
voucher: Optional["Voucher"] = None,
-) -> Tuple[Iterable[CheckoutLineInfo], Iterable[int]]:
+) -> tuple[Iterable[CheckoutLineInfo], Iterable[int]]:
"""Fetch checkout lines as CheckoutLineInfo objects."""
from .utils import get_voucher_for_checkout
@@ -256,7 +253,7 @@ def fetch_checkout_lines(
)
lines_info = []
unavailable_variant_pks = []
- product_channel_listing_mapping: Dict[int, Optional["ProductChannelListing"]] = {}
+ product_channel_listing_mapping: dict[int, Optional["ProductChannelListing"]] = {}
channel = checkout.channel
for line in lines:
@@ -381,7 +378,7 @@ def apply_voucher_to_checkout_line(
from .utils import get_discounted_lines
voucher = voucher_info.voucher
- discounted_lines_by_voucher: List[CheckoutLineInfo] = []
+ discounted_lines_by_voucher: list[CheckoutLineInfo] = []
lines_included_in_discount = lines_info
if voucher.type == VoucherType.SPECIFIC_PRODUCT:
discounted_lines_by_voucher.extend(
@@ -533,7 +530,7 @@ def get_valid_internal_shipping_method_list_for_checkout_info(
shipping_address: Optional["Address"],
lines: Iterable[CheckoutLineInfo],
shipping_channel_listings: Iterable[ShippingMethodChannelListing],
-) -> List["ShippingMethodData"]:
+) -> list["ShippingMethodData"]:
from . import base_calculations
from .utils import get_valid_internal_shipping_methods_for_checkout
@@ -576,7 +573,7 @@ def get_valid_external_shipping_method_list_for_checkout_info(
shipping_address: Optional["Address"],
lines: Iterable[CheckoutLineInfo],
manager: "PluginsManager",
-) -> List["ShippingMethodData"]:
+) -> list["ShippingMethodData"]:
return manager.list_shipping_methods_for_checkout(
checkout=checkout_info.checkout, channel_slug=checkout_info.channel.slug
)
diff --git a/saleor/checkout/migrations/0001_auto_20170113_0435.py b/saleor/checkout/migrations/0001_auto_20170113_0435.py
index a25e423f42..e0f5329d4e 100644
--- a/saleor/checkout/migrations/0001_auto_20170113_0435.py
+++ b/saleor/checkout/migrations/0001_auto_20170113_0435.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2017-01-13 10:35
-from __future__ import unicode_literals
from django.contrib.postgres import fields
from django.db import migrations
diff --git a/saleor/checkout/migrations/0001_initial.py b/saleor/checkout/migrations/0001_initial.py
index 7887d452b7..e42ee0a65e 100644
--- a/saleor/checkout/migrations/0001_initial.py
+++ b/saleor/checkout/migrations/0001_initial.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
import uuid
import django.core.validators
diff --git a/saleor/checkout/migrations/0002_auto_20161014_1221.py b/saleor/checkout/migrations/0002_auto_20161014_1221.py
index f9da82f4a8..b689f7c20d 100644
--- a/saleor/checkout/migrations/0002_auto_20161014_1221.py
+++ b/saleor/checkout/migrations/0002_auto_20161014_1221.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.1 on 2016-10-14 17:21
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/checkout/migrations/0002_auto_20170206_0407.py b/saleor/checkout/migrations/0002_auto_20170206_0407.py
index b1f7794da1..18649f90a6 100644
--- a/saleor/checkout/migrations/0002_auto_20170206_0407.py
+++ b/saleor/checkout/migrations/0002_auto_20170206_0407.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-06 10:07
-from __future__ import unicode_literals
import django.db.models.deletion
from django.contrib.postgres import fields
diff --git a/saleor/checkout/migrations/0003_auto_20170906_0556.py b/saleor/checkout/migrations/0003_auto_20170906_0556.py
index 743b9847db..e839fe2850 100644
--- a/saleor/checkout/migrations/0003_auto_20170906_0556.py
+++ b/saleor/checkout/migrations/0003_auto_20170906_0556.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-06 10:56
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/checkout/migrations/0004_auto_20171129_1004.py b/saleor/checkout/migrations/0004_auto_20171129_1004.py
index 981dce485a..99651b3bbe 100644
--- a/saleor/checkout/migrations/0004_auto_20171129_1004.py
+++ b/saleor/checkout/migrations/0004_auto_20171129_1004.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-29 16:04
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/checkout/migrations/0005_auto_20180108_0814.py b/saleor/checkout/migrations/0005_auto_20180108_0814.py
index 55ef4328e1..38db26df99 100644
--- a/saleor/checkout/migrations/0005_auto_20180108_0814.py
+++ b/saleor/checkout/migrations/0005_auto_20180108_0814.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-08 14:14
-from __future__ import unicode_literals
import uuid
diff --git a/saleor/checkout/migrations/fix_empty_data_in_lines.py b/saleor/checkout/migrations/fix_empty_data_in_lines.py
index 40ac2bf8cf..ac468dab2d 100644
--- a/saleor/checkout/migrations/fix_empty_data_in_lines.py
+++ b/saleor/checkout/migrations/fix_empty_data_in_lines.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-06 13:02
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 23e454a61b..ec202e70eb 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -1,8 +1,9 @@
"""Checkout-related ORM models."""
+from collections.abc import Iterable
from datetime import date
from decimal import Decimal
from operator import attrgetter
-from typing import TYPE_CHECKING, Iterable, Optional, Union
+from typing import TYPE_CHECKING, Optional, Union
from uuid import uuid4
from django.conf import settings
@@ -310,7 +311,7 @@ class CheckoutLine(ModelWithMetadata):
return not self == other # pragma: no cover
def __repr__(self):
- return "CheckoutLine(variant=%r, quantity=%r)" % (self.variant, self.quantity)
+ return f"CheckoutLine(variant={self.variant!r}, quantity={self.quantity!r})"
def __getstate__(self):
return self.variant, self.quantity
diff --git a/saleor/checkout/payment_utils.py b/saleor/checkout/payment_utils.py
index 6ee5b86612..53a6b27361 100644
--- a/saleor/checkout/payment_utils.py
+++ b/saleor/checkout/payment_utils.py
@@ -1,5 +1,6 @@
"""Checkout-related utility functions."""
-from typing import TYPE_CHECKING, Iterable, Optional, Tuple
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional
from prices import Money
@@ -49,7 +50,7 @@ def _update_authorize_status(
def _get_payment_amount_for_checkout(
checkout_transactions: Iterable["TransactionItem"], currency: str
-) -> Tuple[Money, Money]:
+) -> tuple[Money, Money]:
total_charged_amount = zero_money(currency)
total_authorized_amount = zero_money(currency)
for transaction in checkout_transactions:
diff --git a/saleor/checkout/problems.py b/saleor/checkout/problems.py
index fd5acea256..62c6c01122 100644
--- a/saleor/checkout/problems.py
+++ b/saleor/checkout/problems.py
@@ -1,7 +1,8 @@
import datetime
from collections import defaultdict
+from collections.abc import Iterable
from dataclasses import dataclass
-from typing import Iterable, Optional, Tuple, Union
+from typing import Optional, Union
import pytz
@@ -50,7 +51,7 @@ def get_insufficient_stock_lines(
Iterable[Stock],
],
country_code: str,
-) -> list[Tuple["CheckoutLineInfo", int]]:
+) -> list[tuple["CheckoutLineInfo", int]]:
"""Return checkout lines with insufficient stock."""
variant_to_quantity_map: dict[int, int] = defaultdict(int)
variant_to_available_quantity_map: dict[int, int] = defaultdict(int)
diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.py
index f15c44e049..a7d302ba78 100644
--- a/saleor/checkout/tasks.py
+++ b/saleor/checkout/tasks.py
@@ -1,5 +1,4 @@
import logging
-from typing import Tuple
from celery.utils.log import get_task_logger
from django.conf import settings
@@ -18,7 +17,7 @@ def delete_expired_checkouts(
batch_count: int = 5,
invocation_count: int = 1,
invocation_limit: int = 500,
-) -> Tuple[int, bool]:
+) -> tuple[int, bool]:
"""Delete inactive checkouts from the database.
Inactivity is based on the "Checkout.last_change" datetime column.
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index 76bcb894f8..e238799ba1 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -247,9 +247,8 @@ def test_get_prices_of_discounted_specific_product_all_products(
def test_checkout_line_repr(product, checkout_with_single_item):
variant = product.variants.get()
line = checkout_with_single_item.lines.first()
- assert repr(line) == "CheckoutLine(variant=%r, quantity=%r)" % (
- variant,
- line.quantity,
+ assert (
+ repr(line) == f"CheckoutLine(variant={variant!r}, quantity={line.quantity!r})"
)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index a15d499708..682b069d4e 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1,6 +1,7 @@
"""Checkout-related utility functions."""
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union, cast
+from typing import TYPE_CHECKING, Optional, Union, cast
import graphene
from django.core.exceptions import ValidationError
@@ -60,7 +61,7 @@ def invalidate_checkout_prices(
*,
recalculate_discount: bool = True,
save: bool,
-) -> List[str]:
+) -> list[str]:
"""Mark checkout as ready for prices recalculation."""
checkout = checkout_info.checkout
@@ -90,9 +91,9 @@ def check_variant_in_stock(
quantity: int = 1,
replace: bool = False,
check_quantity: bool = True,
- checkout_lines: Optional[List["CheckoutLine"]] = None,
+ checkout_lines: Optional[list["CheckoutLine"]] = None,
check_reservations: bool = False,
-) -> Tuple[int, Optional[CheckoutLine]]:
+) -> tuple[int, Optional[CheckoutLine]]:
"""Check if a given variant is in stock and return the new quantity + line."""
line = checkout.lines.filter(variant=variant).first()
line_quantity = 0 if line is None else line.quantity
@@ -101,7 +102,7 @@ def check_variant_in_stock(
if new_quantity < 0:
raise ValueError(
- "%r is not a valid quantity (results in %r)" % (quantity, new_quantity)
+ f"{quantity!r} is not a valid quantity (results in {new_quantity!r})"
)
if new_quantity > 0 and check_quantity:
@@ -207,9 +208,9 @@ def add_variants_to_checkout(
lines_by_id = {str(line.pk): line for line in checkout_lines}
variants_map = {str(variant.pk): variant for variant in variants}
- to_create: List[CheckoutLine] = []
- to_update: List[CheckoutLine] = []
- to_delete: List[CheckoutLine] = []
+ to_create: list[CheckoutLine] = []
+ to_update: list[CheckoutLine] = []
+ to_delete: list[CheckoutLine] = []
for line_data in checkout_lines_data:
line = lines_by_id.get(line_data.line_id) if line_data.line_id else None
@@ -326,7 +327,7 @@ def _check_new_checkout_address(checkout, address, address_type):
return has_address_changed, remove_old_address
-def change_billing_address_in_checkout(checkout, address) -> List[str]:
+def change_billing_address_in_checkout(checkout, address) -> list[str]:
"""Save billing address in checkout if changed.
Remove previously saved address if not connected to any user.
@@ -436,7 +437,7 @@ def get_discounted_lines(
def get_prices_of_discounted_specific_product(
lines: Iterable["CheckoutLineInfo"],
voucher: Voucher,
-) -> List[Money]:
+) -> list[Money]:
"""Get prices of variants belonging to the discounted specific products.
Specific products are products, collections and categories.
@@ -784,7 +785,7 @@ def get_valid_internal_shipping_methods_for_checkout(
subtotal: "Money",
shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
country_code: Optional[str] = None,
-) -> List[ShippingMethodData]:
+) -> list[ShippingMethodData]:
if not is_shipping_required(lines):
return []
if not checkout_info.shipping_address:
@@ -802,7 +803,7 @@ def get_valid_internal_shipping_methods_for_checkout(
listing.shipping_method_id: listing for listing in shipping_channel_listings
}
- internal_methods: List[ShippingMethodData] = []
+ internal_methods: list[ShippingMethodData] = []
for method in shipping_methods:
listing = channel_listings_map.get(method.pk)
if listing:
diff --git a/saleor/core/anonymize.py b/saleor/core/anonymize.py
index bf098c26f6..db8a962302 100644
--- a/saleor/core/anonymize.py
+++ b/saleor/core/anonymize.py
@@ -3,7 +3,7 @@ def obfuscate_email(value):
if "@" not in str(string_rep):
return obfuscate_string(string_rep)
local_part, domain = str(string_rep).split("@")
- return "{}...@{}".format(local_part[:1], domain)
+ return f"{local_part[:1]}...@{domain}"
def obfuscate_string(value, phone=False):
diff --git a/saleor/core/db/fields.py b/saleor/core/db/fields.py
index d6b6b9e113..8a7f185654 100644
--- a/saleor/core/db/fields.py
+++ b/saleor/core/db/fields.py
@@ -9,7 +9,7 @@ class SanitizedJSONField(JSONField):
"before saving into the database."
def __init__(self, *args, sanitizer: Callable[[dict], dict], **kwargs):
- super(SanitizedJSONField, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
self._sanitizer_method = sanitizer
def deconstruct(self):
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index b35aab01d2..58ff148c6b 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -1,6 +1,7 @@
+from collections.abc import Iterable
from dataclasses import dataclass
from enum import Enum
-from typing import TYPE_CHECKING, Iterable, List, Optional, Union
+from typing import TYPE_CHECKING, Optional, Union
from uuid import UUID
from graphql import GraphQLError
@@ -23,7 +24,7 @@ class InsufficientStockData:
class InsufficientStock(Exception):
- def __init__(self, items: List[InsufficientStockData]):
+ def __init__(self, items: list[InsufficientStockData]):
details = [str(item.variant or item.order_line) for item in items]
super().__init__(f"Insufficient stock for {', '.join(details)}")
self.items = items
@@ -85,7 +86,7 @@ class CircularSubscriptionSyncEvent(GraphQLError):
class SyncEventError(Exception):
def __init__(self, message, code=None):
- super(SyncEventError, self).__init__(message, code)
+ super().__init__(message, code)
self.message = message
self.code = code
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.py
index 07056b83f3..83fa81bccb 100644
--- a/saleor/core/jwt.py
+++ b/saleor/core/jwt.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from datetime import datetime, timedelta
-from typing import Any, Dict, Iterable, Optional
+from typing import Any, Optional
import graphene
import jwt
@@ -29,7 +30,7 @@ JWT_OWNER_FIELD = "owner"
def jwt_base_payload(
exp_delta: Optional[timedelta], token_owner: str
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
utc_now = datetime.utcnow()
payload = {
@@ -46,9 +47,9 @@ def jwt_user_payload(
user: User,
token_type: str,
exp_delta: Optional[timedelta],
- additional_payload: Optional[Dict[str, Any]] = None,
+ additional_payload: Optional[dict[str, Any]] = None,
token_owner: str = JWT_SALEOR_OWNER_NAME,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
payload = jwt_base_payload(exp_delta, token_owner)
payload.update(
{
@@ -64,14 +65,14 @@ def jwt_user_payload(
return payload
-def jwt_encode(payload: Dict[str, Any]) -> str:
+def jwt_encode(payload: dict[str, Any]) -> str:
jwt_manager = get_jwt_manager()
return jwt_manager.encode(payload)
def jwt_decode_with_exception_handler(
token: str, verify_expiration=settings.JWT_EXPIRE
-) -> Optional[Dict[str, Any]]:
+) -> Optional[dict[str, Any]]:
try:
return jwt_decode(token, verify_expiration=verify_expiration)
except jwt.PyJWTError:
@@ -80,18 +81,18 @@ def jwt_decode_with_exception_handler(
def jwt_decode(
token: str, verify_expiration=settings.JWT_EXPIRE, verify_aud: bool = False
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
jwt_manager = get_jwt_manager()
return jwt_manager.decode(token, verify_expiration, verify_aud=verify_aud)
-def create_token(payload: Dict[str, Any], exp_delta: timedelta) -> str:
+def create_token(payload: dict[str, Any], exp_delta: timedelta) -> str:
payload.update(jwt_base_payload(exp_delta, token_owner=JWT_SALEOR_OWNER_NAME))
return jwt_encode(payload)
def create_access_token(
- user: User, additional_payload: Optional[Dict[str, Any]] = None
+ user: User, additional_payload: Optional[dict[str, Any]] = None
) -> str:
payload = jwt_user_payload(
user, JWT_ACCESS_TYPE, settings.JWT_TTL_ACCESS, additional_payload
@@ -100,7 +101,7 @@ def create_access_token(
def create_refresh_token(
- user: User, additional_payload: Optional[Dict[str, Any]] = None
+ user: User, additional_payload: Optional[dict[str, Any]] = None
) -> str:
payload = jwt_user_payload(
user,
@@ -111,7 +112,7 @@ def create_refresh_token(
return jwt_encode(payload)
-def get_user_from_payload(payload: Dict[str, Any], request=None) -> Optional[User]:
+def get_user_from_payload(payload: dict[str, Any], request=None) -> Optional[User]:
# TODO: dataloader
user = User.objects.filter(email=payload["email"], is_active=True).first()
user_jwt_token = payload.get("token")
@@ -162,7 +163,7 @@ def _create_access_token_for_third_party_actions(
permissions: Iterable["Permission"],
user: "User",
app: "App",
- extra: Optional[Dict[str, Any]] = None,
+ extra: Optional[dict[str, Any]] = None,
):
app_permission_enums = get_permission_names(permissions)
diff --git a/saleor/core/payments.py b/saleor/core/payments.py
index c8ed53659b..0fd3a5e6b8 100644
--- a/saleor/core/payments.py
+++ b/saleor/core/payments.py
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING, Iterable, List, Optional
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
@@ -22,7 +23,7 @@ class PaymentInterface(ABC):
checkout_lines: Optional[Iterable["CheckoutLineInfo"]] = None,
channel_slug: Optional[str] = None,
active_only: bool = True,
- ) -> List["PaymentGateway"]:
+ ) -> list["PaymentGateway"]:
pass
@abstractmethod
@@ -76,5 +77,5 @@ class PaymentInterface(ABC):
@abstractmethod
def list_payment_sources(
self, gateway: str, customer_id: str, channel_slug: str
- ) -> List["CustomerSource"]:
+ ) -> list["CustomerSource"]:
pass
diff --git a/saleor/core/postgres.py b/saleor/core/postgres.py
index ae29d86b5f..45849c9a61 100644
--- a/saleor/core/postgres.py
+++ b/saleor/core/postgres.py
@@ -1,5 +1,5 @@
import logging
-from typing import List, Optional, Union
+from typing import Optional, Union
from django.conf import settings
from django.contrib.postgres.search import (
@@ -86,7 +86,7 @@ class FlatConcat(Expression):
expressions = expressions[: self.max_expression_count]
else:
raise ValueError("Maximum expression count exceeded")
- self.source_expressions: List[SearchVector] = self._parse_expressions( # type: ignore[attr-defined] # private method of BaseExpression # noqa: E501
+ self.source_expressions: list[SearchVector] = self._parse_expressions( # type: ignore[attr-defined] # private method of BaseExpression # noqa: E501
*expressions
)
@@ -126,8 +126,8 @@ class FlatConcat(Expression):
def as_sql(self, compiler, connection, **_extra_context):
connection.ops.check_expression_support(self)
- sql_parts: List[str] = []
- params: List[Optional[Union[str, int]]] = []
+ sql_parts: list[str] = []
+ params: list[Optional[Union[str, int]]] = []
for arg in self.source_expressions:
arg_sql, arg_params = compiler.compile(arg)
sql_parts.append(arg_sql)
diff --git a/saleor/core/prices.py b/saleor/core/prices.py
index efc2eb77e2..b8be0d03d5 100644
--- a/saleor/core/prices.py
+++ b/saleor/core/prices.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, TypeVar
+from typing import TYPE_CHECKING, TypeVar
from babel.numbers import get_currency_precision
from prices import Money, TaxedMoney, TaxedMoneyRange
diff --git a/saleor/core/schedules.py b/saleor/core/schedules.py
index da21fa706e..dfae17bf80 100644
--- a/saleor/core/schedules.py
+++ b/saleor/core/schedules.py
@@ -78,21 +78,17 @@ class promotion_webhook_schedule(CustomSchedule):
upcoming_start_dates = Promotion.objects.filter(
(
- (
- Q(last_notification_scheduled_at__isnull=True)
- | Q(last_notification_scheduled_at__lt=F("start_date"))
- )
- & Q(start_date__gt=now)
+ Q(last_notification_scheduled_at__isnull=True)
+ | Q(last_notification_scheduled_at__lt=F("start_date"))
)
+ & Q(start_date__gt=now)
).order_by("start_date")
upcoming_end_dates = Promotion.objects.filter(
(
- (
- Q(last_notification_scheduled_at__isnull=True)
- | Q(last_notification_scheduled_at__lt=F("end_date"))
- )
- & Q(end_date__gt=now)
+ Q(last_notification_scheduled_at__isnull=True)
+ | Q(last_notification_scheduled_at__lt=F("end_date"))
)
+ & Q(end_date__gt=now)
).order_by("end_date")
nearest_start_date = upcoming_start_dates.first()
diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.py
index cd0dd9e719..295b260cd6 100644
--- a/saleor/core/search_tasks.py
+++ b/saleor/core/search_tasks.py
@@ -1,5 +1,3 @@
-from typing import List
-
from celery.utils.log import get_task_logger
from ..account.models import User
@@ -110,7 +108,7 @@ def set_product_search_document_values(updated_count: int = 0) -> None:
set_product_search_document_values.delay(updated_count)
-def set_search_document_values(instances: List, prepare_search_document_func):
+def set_search_document_values(instances: list, prepare_search_document_func):
if not instances:
return 0
Model = instances[0]._meta.model
diff --git a/saleor/core/taxes.py b/saleor/core/taxes.py
index 042d4018a6..dcd246f09b 100644
--- a/saleor/core/taxes.py
+++ b/saleor/core/taxes.py
@@ -1,6 +1,5 @@
from dataclasses import dataclass
from decimal import Decimal
-from typing import List
from prices import Money, TaxedMoney
@@ -42,4 +41,4 @@ class TaxData:
shipping_price_gross_amount: Decimal
shipping_price_net_amount: Decimal
shipping_tax_rate: Decimal
- lines: List[TaxLineData]
+ lines: list[TaxLineData]
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 67c57addb7..5704c76357 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -1,5 +1,6 @@
import socket
-from typing import TYPE_CHECKING, Iterable, Optional, Union
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional, Union
from urllib.parse import urljoin, urlparse
from celery.utils.log import get_task_logger
@@ -74,7 +75,7 @@ def is_valid_ipv4(ip: str) -> bool:
"""Check whether the passed IP is a valid V4 IP address."""
try:
socket.inet_pton(socket.AF_INET, ip)
- except socket.error:
+ except OSError:
return False
return True
@@ -83,7 +84,7 @@ def is_valid_ipv6(ip: str) -> bool:
"""Check whether the passed IP is a valid V6 IP address."""
try:
socket.inet_pton(socket.AF_INET6, ip)
- except socket.error:
+ except OSError:
return False
return True
diff --git a/saleor/core/utils/anonymization.py b/saleor/core/utils/anonymization.py
index 2e9cc55477..de38691cef 100644
--- a/saleor/core/utils/anonymization.py
+++ b/saleor/core/utils/anonymization.py
@@ -1,6 +1,6 @@
import copy
import logging
-from typing import TYPE_CHECKING, Dict
+from typing import TYPE_CHECKING
from faker import Faker
@@ -43,7 +43,7 @@ def generate_fake_user() -> "User":
return fake_user
-def generate_fake_metadata() -> Dict[str, str]:
+def generate_fake_metadata() -> dict[str, str]:
"""Generate a fake metadata/private metadata dictionary."""
return fake.pydict(value_types=str)
diff --git a/saleor/core/utils/draftjs.py b/saleor/core/utils/draftjs.py
index 1aaec53ad9..c29e9fb601 100644
--- a/saleor/core/utils/draftjs.py
+++ b/saleor/core/utils/draftjs.py
@@ -1,7 +1,4 @@
-from typing import Dict
-
-
-def json_content_to_raw_text(content: Dict[str, dict], sep: str = "\n") -> str:
+def json_content_to_raw_text(content: dict[str, dict], sep: str = "\n") -> str:
"""Convert DraftJS JSON content to plain text."""
if not isinstance(content, dict) or "blocks" not in content:
diff --git a/saleor/core/utils/editorjs.py b/saleor/core/utils/editorjs.py
index da574a7b9e..fb54054d38 100644
--- a/saleor/core/utils/editorjs.py
+++ b/saleor/core/utils/editorjs.py
@@ -1,6 +1,6 @@
import re
import warnings
-from typing import Dict, List, Literal, Union, overload
+from typing import Literal, Union, overload
from django.utils.html import strip_tags
from urllib3.util import parse_url
@@ -17,13 +17,13 @@ ITEM_TYPE_TO_CLEAN_FUNC_MAP = {
@overload
def clean_editor_js(
- definitions: Union[Dict, str, None], *, to_string: Literal[True]
+ definitions: Union[dict, str, None], *, to_string: Literal[True]
) -> str:
...
@overload
-def clean_editor_js(definitions: Dict) -> Dict:
+def clean_editor_js(definitions: dict) -> dict:
...
@@ -32,7 +32,7 @@ def clean_editor_js(definitions: None) -> None:
...
-def clean_editor_js(definitions, *, to_string=False) -> Union[Dict, str, None]:
+def clean_editor_js(definitions, *, to_string=False) -> Union[dict, str, None]:
"""Sanitize a given EditorJS JSON definitions.
Look for not allowed URLs, replaced them with `invalid` value, and clean valid ones.
@@ -48,7 +48,7 @@ def clean_editor_js(definitions, *, to_string=False) -> Union[Dict, str, None]:
if not blocks or not isinstance(blocks, list):
return "" if to_string else definitions
- plain_text_list: List[str] = []
+ plain_text_list: list[str] = []
for index, block in enumerate(blocks):
block_type = block["type"]
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index f7e885c91c..084c243af8 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -8,7 +8,7 @@ import uuid
from collections import defaultdict
from decimal import Decimal
from functools import lru_cache
-from typing import Any, Dict, Type, Union, cast
+from typing import Any, Union, cast
from unittest.mock import patch
import graphene
@@ -162,7 +162,7 @@ CATEGORY_IMAGES = {
COLLECTION_IMAGES = {1: "summer.jpg", 2: "clothing.jpg", 3: "clothing.jpg"}
-@lru_cache()
+@lru_cache
def get_sample_data():
path = os.path.join(
settings.PROJECT_ROOT, "saleor", "static", "populatedb_data.json"
@@ -338,7 +338,7 @@ def create_product_variant_channel_listings(product_variant_channel_listings_dat
def assign_attributes_to_product_types(
- association_model: Union[Type[AttributeProduct], Type[AttributeVariant]],
+ association_model: Union[type[AttributeProduct], type[AttributeVariant]],
attributes: list,
):
for value in attributes:
@@ -350,7 +350,7 @@ def assign_attributes_to_product_types(
def assign_attributes_to_page_types(
- association_model: Type[AttributePage],
+ association_model: type[AttributePage],
attributes: list,
):
for value in attributes:
@@ -793,7 +793,7 @@ def create_fake_order(max_order_lines=5, create_preorder_lines=False):
billing_address = customer.default_billing_address
else:
billing_address = address
- order_data: Dict[str, Any] = {
+ order_data: dict[str, Any] = {
"billing_address": billing_address or address,
"shipping_address": address,
"user_email": get_email(address.first_name, address.last_name),
diff --git a/saleor/core/utils/translations.py b/saleor/core/utils/translations.py
index f51281b521..be84a46a60 100644
--- a/saleor/core/utils/translations.py
+++ b/saleor/core/utils/translations.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, Tuple, Union
+from typing import Any, Union
from django.conf import settings
from django.db import models
@@ -33,17 +33,17 @@ class Translation(models.Model):
class Meta:
abstract = True
- def get_translated_object_id(self) -> Tuple[str, Union[int, str]]:
+ def get_translated_object_id(self) -> tuple[str, Union[int, str]]:
raise NotImplementedError(
"Models extending Translation should implement get_translated_object_id"
)
- def get_translated_keys(self) -> Dict[str, Any]:
+ def get_translated_keys(self) -> dict[str, Any]:
raise NotImplementedError(
"Models extending Translation should implement get_translated_keys"
)
- def get_translation_context(self) -> Dict[str, Any]:
+ def get_translation_context(self) -> dict[str, Any]:
return {}
diff --git a/saleor/core/utils/validators.py b/saleor/core/utils/validators.py
index e98223847d..5610477b79 100644
--- a/saleor/core/utils/validators.py
+++ b/saleor/core/utils/validators.py
@@ -1,5 +1,5 @@
from datetime import date
-from typing import Any, Dict, Tuple
+from typing import Any
import micawber
from django.core.exceptions import ValidationError
@@ -15,7 +15,7 @@ MEDIA_MAX_WIDTH = 1920
MEDIA_MAX_HEIGHT = 1080
-def get_oembed_data(url: str, field_name: str) -> Tuple[Dict[str, Any], str]:
+def get_oembed_data(url: str, field_name: str) -> tuple[dict[str, Any], str]:
"""Get the oembed data from URL or raise an ValidationError."""
providers = micawber.bootstrap_basic()
diff --git a/saleor/csv/tasks.py b/saleor/csv/tasks.py
index caf96092ee..1fe8132a6d 100644
--- a/saleor/csv/tasks.py
+++ b/saleor/csv/tasks.py
@@ -1,4 +1,4 @@
-from typing import Dict, Union
+from typing import Union
import celery
from celery.utils.log import get_task_logger
@@ -60,8 +60,8 @@ class ExportTask(celery.Task):
@app.task(name="export-products", base=ExportTask)
def export_products_task(
export_file_id: int,
- scope: Dict[str, Union[str, dict]],
- export_info: Dict[str, list],
+ scope: dict[str, Union[str, dict]],
+ export_info: dict[str, list],
file_type: str,
delimiter: str = ",",
):
@@ -72,7 +72,7 @@ def export_products_task(
@app.task(name="export-gift-cards", base=ExportTask)
def export_gift_cards_task(
export_file_id: int,
- scope: Dict[str, Union[str, dict]],
+ scope: dict[str, Union[str, dict]],
file_type: str,
delimiter: str = ",",
):
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index 37a27d5dd0..4304e5d003 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -85,12 +85,12 @@ def test_get_products_data(product, product_with_image, collection, image, chann
else product.collections.first().slug
),
"product_weight": (
- "{} g".format(int(product.weight.value)) if product.weight else ""
+ f"{int(product.weight.value)} g" if product.weight else ""
),
"media__image": (
""
if not product.media.all()
- else "http://mirumee.com{}".format(product.media.first().image.url)
+ else f"http://mirumee.com{product.media.first().image.url}"
),
}
@@ -110,7 +110,7 @@ def test_get_products_data(product, product_with_image, collection, image, chann
"variants__media__image": (
""
if not variant.media.all()
- else "http://mirumee.com{}".format(variant.media.first().image.url)
+ else f"http://mirumee.com{variant.media.first().image.url}"
),
"variant_weight": (
"{} g".foramt(int(variant.weight.value)) if variant.weight else ""
diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.py
index 9c78f54937..c2e20df7f6 100644
--- a/saleor/csv/utils/export.py
+++ b/saleor/csv/utils/export.py
@@ -1,7 +1,7 @@
import uuid
from datetime import date, datetime
from tempfile import NamedTemporaryFile
-from typing import IO, TYPE_CHECKING, Any, Dict, List, Set, Union
+from typing import IO, TYPE_CHECKING, Any, Union
import petl as etl
from django.utils import timezone
@@ -24,8 +24,8 @@ BATCH_SIZE = 10000
def export_products(
export_file: "ExportFile",
- scope: Dict[str, Union[str, dict]],
- export_info: Dict[str, list],
+ scope: dict[str, Union[str, dict]],
+ export_info: dict[str, list],
file_type: str,
delimiter: str = ",",
):
@@ -60,7 +60,7 @@ def export_products(
def export_gift_cards(
export_file: "ExportFile",
- scope: Dict[str, Union[str, dict]],
+ scope: dict[str, Union[str, dict]],
file_type: str,
delimiter: str = ",",
):
@@ -96,7 +96,7 @@ def get_filename(model_name: str, file_type: str) -> str:
)
-def get_queryset(model, filter, scope: Dict[str, Union[str, dict]]) -> "QuerySet":
+def get_queryset(model, filter, scope: dict[str, Union[str, dict]]) -> "QuerySet":
queryset = model.objects.all()
if "ids" in scope:
queryset = model.objects.filter(pk__in=scope["ids"])
@@ -108,7 +108,7 @@ def get_queryset(model, filter, scope: Dict[str, Union[str, dict]]) -> "QuerySet
return queryset
-def parse_input(data: Any) -> Dict[str, Union[str, dict]]:
+def parse_input(data: Any) -> dict[str, Union[str, dict]]:
"""Parse input into correct data types.
Scope coming from Celery will be passed as strings.
@@ -137,7 +137,7 @@ def parse_input(data: Any) -> Dict[str, Union[str, dict]]:
return data
-def create_file_with_headers(file_headers: List[str], delimiter: str, file_type: str):
+def create_file_with_headers(file_headers: list[str], delimiter: str, file_type: str):
table = etl.wrap([file_headers])
if file_type == FileTypes.CSV:
@@ -152,9 +152,9 @@ def create_file_with_headers(file_headers: List[str], delimiter: str, file_type:
def export_products_in_batches(
queryset: "QuerySet",
- export_info: Dict[str, list],
- export_fields: Set[str],
- headers: List[str],
+ export_info: dict[str, list],
+ export_fields: set[str],
+ headers: list[str],
delimiter: str,
temporary_file: Any,
file_type: str,
@@ -182,7 +182,7 @@ def export_products_in_batches(
def export_gift_cards_in_batches(
queryset: "QuerySet",
- export_fields: List[str],
+ export_fields: list[str],
delimiter: str,
temporary_file: Any,
file_type: str,
@@ -215,8 +215,8 @@ def queryset_in_batches(queryset):
def append_to_file(
- export_data: List[Dict[str, Union[str, bool]]],
- headers: List[str],
+ export_data: list[dict[str, Union[str, bool]]],
+ headers: list[str],
temporary_file: Any,
file_type: str,
delimiter: str,
diff --git a/saleor/csv/utils/product_headers.py b/saleor/csv/utils/product_headers.py
index 55662230e9..c6e5039df2 100644
--- a/saleor/csv/utils/product_headers.py
+++ b/saleor/csv/utils/product_headers.py
@@ -1,5 +1,4 @@
from collections import ChainMap
-from typing import Dict, List, Tuple
from django.db.models import Value as V
from django.db.models.functions import Concat
@@ -11,8 +10,8 @@ from . import ProductExportFields
def get_product_export_fields_and_headers_info(
- export_info: Dict[str, list]
-) -> Tuple[List[str], List[str], List[str]]:
+ export_info: dict[str, list]
+) -> tuple[list[str], list[str], list[str]]:
"""Get export fields, all headers and headers mapping.
Based on export_info returns exported fields, fields to headers mapping and
@@ -32,8 +31,8 @@ def get_product_export_fields_and_headers_info(
def get_product_export_fields_and_headers(
- export_info: Dict[str, list]
-) -> Tuple[List[str], List[str]]:
+ export_info: dict[str, list]
+) -> tuple[list[str], list[str]]:
"""Get export fields from export info and prepare headers mapping.
Based on given fields headers from export info, export fields set and
@@ -59,7 +58,7 @@ def get_product_export_fields_and_headers(
return export_fields, file_headers
-def get_attributes_headers(export_info: Dict[str, list]) -> List[str]:
+def get_attributes_headers(export_info: dict[str, list]) -> list[str]:
"""Get headers for exported attributes.
Headers are build from slug and contains information if it's a product or variant
@@ -90,7 +89,7 @@ def get_attributes_headers(export_info: Dict[str, list]) -> List[str]:
return list(products_headers) + list(variant_headers)
-def get_warehouses_headers(export_info: Dict[str, list]) -> List[str]:
+def get_warehouses_headers(export_info: dict[str, list]) -> list[str]:
"""Get headers for exported warehouses.
Headers are build from slug. Example: "slug-value (warehouse quantity)"
@@ -109,7 +108,7 @@ def get_warehouses_headers(export_info: Dict[str, list]) -> List[str]:
return list(warehouses_headers)
-def get_channels_headers(export_info: Dict[str, list]) -> List[str]:
+def get_channels_headers(export_info: dict[str, list]) -> list[str]:
"""Get headers for exported channels.
Headers are build from slug and exported field.
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index dd6c4f77ed..431e6585c1 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union
+from typing import TYPE_CHECKING, Optional, Union
from urllib.parse import urljoin
import graphene
@@ -20,11 +20,11 @@ if TYPE_CHECKING:
def get_products_data(
queryset: "QuerySet",
- export_fields: Set[str],
- attribute_ids: Optional[List[str]],
- warehouse_ids: Optional[List[str]],
- channel_ids: Optional[List[str]],
-) -> List[Dict[str, Union[str, bool]]]:
+ export_fields: set[str],
+ attribute_ids: Optional[list[str]],
+ warehouse_ids: Optional[list[str]],
+ channel_ids: Optional[list[str]],
+) -> list[dict[str, Union[str, bool]]]:
"""Create data list of products and their variants with fields values.
It return list with product and variant data which can be used as import to
@@ -78,8 +78,8 @@ def get_products_data(
else:
variant_pk = product_data.pop("variants__id")
- product_relations_data: Dict[str, str] = products_relations_data.get(pk, {})
- variant_relations_data: Dict[str, str] = variants_relations_data.get(
+ product_relations_data: dict[str, str] = products_relations_data.get(pk, {})
+ variant_relations_data: dict[str, str] = variants_relations_data.get(
variant_pk, {}
)
@@ -98,10 +98,10 @@ def get_products_data(
def get_products_relations_data(
queryset: "QuerySet",
- export_fields: Set[str],
- attribute_ids: Optional[List[str]],
- channel_ids: Optional[List[str]],
-) -> Dict[int, Dict[str, str]]:
+ export_fields: set[str],
+ attribute_ids: Optional[list[str]],
+ channel_ids: Optional[list[str]],
+) -> dict[int, dict[str, str]]:
"""Get data about product relations fields.
If any many to many fields are in export_fields or some attribute_ids exists then
@@ -122,17 +122,17 @@ def get_products_relations_data(
def prepare_products_relations_data(
queryset: "QuerySet",
- fields: Set[str],
- attribute_ids: Optional[List[str]],
- channel_ids: Optional[List[str]],
-) -> Dict[int, Dict[str, str]]:
+ fields: set[str],
+ attribute_ids: Optional[list[str]],
+ channel_ids: Optional[list[str]],
+) -> dict[int, dict[str, str]]:
"""Prepare data about products relation fields for given queryset.
It return dict where key is a product pk, value is a dict with relation fields data.
"""
attribute_fields = ProductExportFields.PRODUCT_ATTRIBUTE_FIELDS
channel_fields = ProductExportFields.PRODUCT_CHANNEL_LISTING_FIELDS.copy()
- result_data: Dict[int, dict] = defaultdict(dict)
+ result_data: dict[int, dict] = defaultdict(dict)
fields.add("pk")
if attribute_ids:
@@ -165,7 +165,7 @@ def prepare_products_relations_data(
channel_fields,
)
- result: Dict[int, Dict[str, str]] = {
+ result: dict[int, dict[str, str]] = {
pk: {
header: ", ".join(sorted(values)) if isinstance(values, set) else values
for header, values in data.items()
@@ -177,11 +177,11 @@ def prepare_products_relations_data(
def get_variants_relations_data(
queryset: "QuerySet",
- export_fields: Set[str],
- attribute_ids: Optional[List[str]],
- warehouse_ids: Optional[List[str]],
- channel_ids: Optional[List[str]],
-) -> Dict[int, Dict[str, str]]:
+ export_fields: set[str],
+ attribute_ids: Optional[list[str]],
+ warehouse_ids: Optional[list[str]],
+ channel_ids: Optional[list[str]],
+) -> dict[int, dict[str, str]]:
"""Get data about variants relations fields.
If any many to many fields are in export_fields or some attribute_ids or
@@ -202,11 +202,11 @@ def get_variants_relations_data(
def prepare_variants_relations_data(
queryset: "QuerySet",
- fields: Set[str],
- attribute_ids: Optional[List[str]],
- warehouse_ids: Optional[List[str]],
- channel_ids: Optional[List[str]],
-) -> Dict[int, Dict[str, str]]:
+ fields: set[str],
+ attribute_ids: Optional[list[str]],
+ warehouse_ids: Optional[list[str]],
+ channel_ids: Optional[list[str]],
+) -> dict[int, dict[str, str]]:
"""Prepare data about variants relation fields for given queryset.
It return dict where key is a product pk, value is a dict with relation fields data.
@@ -215,7 +215,7 @@ def prepare_variants_relations_data(
warehouse_fields = ProductExportFields.WAREHOUSE_FIELDS
channel_fields = ProductExportFields.VARIANT_CHANNEL_LISTING_FIELDS.copy()
- result_data: Dict[int, dict] = defaultdict(dict)
+ result_data: dict[int, dict] = defaultdict(dict)
fields.add("variants__pk")
if attribute_ids:
@@ -253,7 +253,7 @@ def prepare_variants_relations_data(
pk, data, warehouse_ids, result_data, warehouse_fields
)
- result: Dict[int, Dict[str, str]] = {
+ result: dict[int, dict[str, str]] = {
pk: {
header: ", ".join(sorted(values)) if isinstance(values, set) else values
for header, values in data.items()
@@ -264,8 +264,8 @@ def prepare_variants_relations_data(
def add_collection_info_to_data(
- pk: int, collection: str, result_data: Dict[int, dict]
-) -> Dict[int, dict]:
+ pk: int, collection: str, result_data: dict[int, dict]
+) -> dict[int, dict]:
"""Add collection info to product data.
This functions adds info about collection to dict with product data.
@@ -284,8 +284,8 @@ def add_collection_info_to_data(
def add_image_uris_to_data(
- pk: int, image: str, header: str, result_data: Dict[int, dict]
-) -> Dict[int, dict]:
+ pk: int, image: str, header: str, result_data: dict[int, dict]
+) -> dict[int, dict]:
"""Add absolute uri of given image path to product or variant data.
This function based on given image path creates absolute uri and adds it to dict
@@ -322,8 +322,8 @@ class AttributeData:
def handle_attribute_data(
pk: int,
data: dict,
- attribute_ids: Optional[List[str]],
- result_data: Dict[int, dict],
+ attribute_ids: Optional[list[str]],
+ result_data: dict[int, dict],
attribute_fields: dict,
attribute_owner: str,
):
@@ -347,8 +347,8 @@ def handle_attribute_data(
def handle_channel_data(
pk: int,
data: dict,
- channel_ids: Optional[List[str]],
- result_data: Dict[int, dict],
+ channel_ids: Optional[list[str]],
+ result_data: dict[int, dict],
pk_lookup: str,
slug_lookup: str,
fields: dict,
@@ -373,8 +373,8 @@ def handle_channel_data(
def handle_warehouse_data(
pk: int,
data: dict,
- warehouse_ids: Optional[List[str]],
- result_data: Dict[int, dict],
+ warehouse_ids: Optional[list[str]],
+ result_data: dict[int, dict],
warehouse_fields: dict,
):
warehouse_data: dict = {}
@@ -395,8 +395,8 @@ def add_attribute_info_to_data(
pk: int,
attribute_data: AttributeData,
attribute_owner: str,
- result_data: Dict[int, dict],
-) -> Dict[int, dict]:
+ result_data: dict[int, dict],
+) -> dict[int, dict]:
"""Add info about attribute to variant or product data.
This functions adds info about attribute to dict with variant or product data.
@@ -481,9 +481,9 @@ def _get_reference_value(attribute_data):
def add_warehouse_info_to_data(
pk: int,
- warehouse_data: Dict[str, Union[Optional[str]]],
- result_data: Dict[int, dict],
-) -> Dict[int, dict]:
+ warehouse_data: dict[str, Union[Optional[str]]],
+ result_data: dict[int, dict],
+) -> dict[int, dict]:
"""Add info about stock quantity to variant data.
This functions adds info about stock quantity to dict with variant data.
@@ -501,10 +501,10 @@ def add_warehouse_info_to_data(
def add_channel_info_to_data(
pk: int,
- channel_data: Dict[str, Union[Optional[str]]],
- result_data: Dict[int, dict],
- fields: List[str],
-) -> Dict[int, dict]:
+ channel_data: dict[str, Union[Optional[str]]],
+ result_data: dict[int, dict],
+ fields: list[str],
+) -> dict[int, dict]:
"""Add info about channel currency code, whether is published and publication date.
This functions adds info about channel to dict with product data.
diff --git a/saleor/demo/views.py b/saleor/demo/views.py
index f5e9eaecb9..d51ab6c576 100644
--- a/saleor/demo/views.py
+++ b/saleor/demo/views.py
@@ -3,7 +3,7 @@ from django.shortcuts import render
from ..graphql.views import GraphQLView
-EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
+EXAMPLE_QUERY = f"""# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
@@ -11,18 +11,18 @@ EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Here is an example query to fetch a list of products:
#
-{
- products(first: 5, channel: "%(channel_slug)s") {
- edges {
- node {
+{{
+ products(first: 5, channel: "{settings.DEFAULT_CHANNEL_SLUG}") {{
+ edges {{
+ node {{
id
name
description
- }
- }
- }
-}
-""" % {"channel_slug": settings.DEFAULT_CHANNEL_SLUG}
+ }}
+ }}
+ }}
+}}
+"""
class DemoGraphQLView(GraphQLView):
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index 11eed50b8b..d09cd25d79 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from django.db.models import QuerySet
@@ -76,6 +76,6 @@ class PromotionEvents:
@dataclass
class PromotionRuleInfo:
rule: "PromotionRule"
- variant_ids: List[int]
+ variant_ids: list[int]
variants: QuerySet
- channel_ids: List[int]
+ channel_ids: list[int]
diff --git a/saleor/discount/events.py b/saleor/discount/events.py
index 4eb37b4e8b..629dd9b743 100644
--- a/saleor/discount/events.py
+++ b/saleor/discount/events.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
import graphene
@@ -54,7 +54,7 @@ def promotion_ended_event(
def _rule_base_event(
user: Optional[User],
app: Optional[App],
- rules: List[PromotionRule],
+ rules: list[PromotionRule],
type: str,
):
events = []
@@ -76,7 +76,7 @@ def _rule_base_event(
def rule_created_event(
user: Optional[User],
app: Optional[App],
- rules: List[PromotionRule],
+ rules: list[PromotionRule],
):
return _rule_base_event(
user=user,
@@ -89,7 +89,7 @@ def rule_created_event(
def rule_updated_event(
user: Optional[User],
app: Optional[App],
- rules: List[PromotionRule],
+ rules: list[PromotionRule],
):
return _rule_base_event(
user=user,
@@ -102,7 +102,7 @@ def rule_updated_event(
def rule_deleted_event(
user: Optional[User],
app: Optional[App],
- rules: List[PromotionRule],
+ rules: list[PromotionRule],
):
return _rule_base_event(
user=user,
diff --git a/saleor/discount/interface.py b/saleor/discount/interface.py
index e4bdf87a8d..7945f8ebde 100644
--- a/saleor/discount/interface.py
+++ b/saleor/discount/interface.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass
-from typing import TYPE_CHECKING, List, NamedTuple, Optional
+from typing import TYPE_CHECKING, NamedTuple, Optional
from .models import Voucher
@@ -21,10 +21,10 @@ class VoucherInfo:
"""It contains the voucher's details and PKs of all applicable objects."""
voucher: Voucher
- product_pks: List[int]
- variant_pks: List[int]
- collection_pks: List[int]
- category_pks: List[int]
+ product_pks: list[int]
+ variant_pks: list[int]
+ collection_pks: list[int]
+ category_pks: list[int]
def fetch_voucher_info(voucher: Voucher) -> VoucherInfo:
diff --git a/saleor/discount/migrations/0001_initial.py b/saleor/discount/migrations/0001_initial.py
index 99c40f7df3..342546ad73 100644
--- a/saleor/discount/migrations/0001_initial.py
+++ b/saleor/discount/migrations/0001_initial.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-01-29 14:26
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/discount/migrations/0002_voucher.py b/saleor/discount/migrations/0002_voucher.py
index 02aac70ed8..717b0b9587 100644
--- a/saleor/discount/migrations/0002_voucher.py
+++ b/saleor/discount/migrations/0002_voucher.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-02-04 17:07
-from __future__ import unicode_literals
import datetime
import os
diff --git a/saleor/discount/migrations/0003_auto_20160207_0534.py b/saleor/discount/migrations/0003_auto_20160207_0534.py
index bb65a763be..9b7647eb27 100644
--- a/saleor/discount/migrations/0003_auto_20160207_0534.py
+++ b/saleor/discount/migrations/0003_auto_20160207_0534.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-02-07 11:34
-from __future__ import unicode_literals
import datetime
import os
diff --git a/saleor/discount/migrations/0004_auto_20170206_0407.py b/saleor/discount/migrations/0004_auto_20170206_0407.py
index 4494776bd5..9a4f4b52a7 100644
--- a/saleor/discount/migrations/0004_auto_20170206_0407.py
+++ b/saleor/discount/migrations/0004_auto_20170206_0407.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-06 10:07
-from __future__ import unicode_literals
import os
diff --git a/saleor/discount/migrations/0005_auto_20170919_0839.py b/saleor/discount/migrations/0005_auto_20170919_0839.py
index 4ea670c138..398e8200f4 100644
--- a/saleor/discount/migrations/0005_auto_20170919_0839.py
+++ b/saleor/discount/migrations/0005_auto_20170919_0839.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-19 13:39
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/discount/migrations/0006_auto_20171129_1004.py b/saleor/discount/migrations/0006_auto_20171129_1004.py
index 42c1f0d150..d8ae90bbbd 100644
--- a/saleor/discount/migrations/0006_auto_20171129_1004.py
+++ b/saleor/discount/migrations/0006_auto_20171129_1004.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-29 16:04
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/discount/migrations/0007_auto_20180108_0814.py b/saleor/discount/migrations/0007_auto_20180108_0814.py
index 884188a0c4..b67a1d2180 100644
--- a/saleor/discount/migrations/0007_auto_20180108_0814.py
+++ b/saleor/discount/migrations/0007_auto_20180108_0814.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-08 14:14
-from __future__ import unicode_literals
import datetime
import os
diff --git a/saleor/discount/migrations/0047_migrate_sales_to_promotions.py b/saleor/discount/migrations/0047_migrate_sales_to_promotions.py
index 957ddbcd3a..a19791a1ca 100644
--- a/saleor/discount/migrations/0047_migrate_sales_to_promotions.py
+++ b/saleor/discount/migrations/0047_migrate_sales_to_promotions.py
@@ -1,7 +1,6 @@
# Generated by Django 3.2.18 on 2023-07-06 09:43
from dataclasses import dataclass
from decimal import Decimal
-from typing import Dict, List
import graphene
from babel.numbers import get_currency_precision
@@ -127,8 +126,8 @@ def _migrate_sales_with_listing(
OrderLineDiscount,
sales,
):
- saleid_promotion_map: Dict[int, Promotion] = {}
- rules_info: List[RuleInfo] = []
+ saleid_promotion_map: dict[int, Promotion] = {}
+ rules_info: list[RuleInfo] = []
sale_ids = [sale.id for sale in sales]
migrate_sales_to_promotions(Promotion, sales, saleid_promotion_map)
@@ -312,7 +311,7 @@ def create_catalogue_predicate_from_sale(sale):
def create_catalogue_predicate(collection_ids, category_ids, product_ids, variant_ids):
- predicate: Dict[str, List] = {"OR": []}
+ predicate: dict[str, list] = {"OR": []}
if collection_ids:
predicate["OR"].append({"collectionPredicate": {"ids": collection_ids}})
if category_ids:
@@ -330,7 +329,7 @@ def create_catalogue_predicate(collection_ids, category_ids, product_ids, varian
def migrate_sales_to_promotion_rules(PromotionRule, sales, saleid_promotion_map):
if not sales:
return
- rules: List[PromotionRule] = []
+ rules: list[PromotionRule] = []
for sale in sales:
promotion = saleid_promotion_map[sale.id]
rules.append(create_promotion_rule(PromotionRule, sale, promotion))
diff --git a/saleor/discount/migrations/0051_detach_sale_from_permission.py b/saleor/discount/migrations/0051_detach_sale_from_permission.py
index d42d545565..b52ab70968 100644
--- a/saleor/discount/migrations/0051_detach_sale_from_permission.py
+++ b/saleor/discount/migrations/0051_detach_sale_from_permission.py
@@ -65,7 +65,7 @@ def _get_builtin_permissions(opts): # noqa: D205, D212
perms.append(
(
get_permission_codename(action, opts),
- "Can %s %s" % (action, opts.verbose_name_raw),
+ f"Can {action} {opts.verbose_name_raw}",
)
)
return perms
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
index 8157d01118..c46a9abe37 100644
--- a/saleor/discount/tasks.py
+++ b/saleor/discount/tasks.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from datetime import datetime
-from typing import TYPE_CHECKING, Dict
+from typing import TYPE_CHECKING
import graphene
import pytz
@@ -103,12 +103,10 @@ def get_starting_promotions():
now = datetime.now(pytz.UTC)
promotions = Promotion.objects.filter(
(
- (
- Q(last_notification_scheduled_at__isnull=True)
- | Q(last_notification_scheduled_at__lt=F("start_date"))
- )
- & Q(start_date__lte=now)
+ Q(last_notification_scheduled_at__isnull=True)
+ | Q(last_notification_scheduled_at__lt=F("start_date"))
)
+ & Q(start_date__lte=now)
)
return promotions
@@ -123,19 +121,17 @@ def get_ending_promotions():
now = datetime.now(pytz.UTC)
promotions = Promotion.objects.filter(
(
- (
- Q(last_notification_scheduled_at__isnull=True)
- | Q(last_notification_scheduled_at__lt=F("end_date"))
- )
- & Q(end_date__lte=now)
+ Q(last_notification_scheduled_at__isnull=True)
+ | Q(last_notification_scheduled_at__lt=F("end_date"))
)
+ & Q(end_date__lte=now)
)
return promotions
def fetch_promotion_variants_and_product_ids(promotions: "QuerySet[Promotion]"):
"""Fetch products that are included in the given promotions."""
- promotion_id_to_variants: Dict[UUID, "QuerySet"] = defaultdict(
+ promotion_id_to_variants: dict[UUID, "QuerySet"] = defaultdict(
lambda: ProductVariant.objects.none()
)
variants = ProductVariant.objects.none()
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 479db3cab4..517434415e 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -1,18 +1,12 @@
import datetime
from collections import defaultdict
+from collections.abc import Iterable, Iterator
from decimal import ROUND_HALF_UP, Decimal
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
- DefaultDict,
- Dict,
- Iterable,
- Iterator,
- List,
Optional,
- Set,
- Tuple,
Union,
cast,
)
@@ -47,7 +41,7 @@ if TYPE_CHECKING:
)
from .models import Voucher
-CatalogueInfo = DefaultDict[str, Set[Union[int, str]]]
+CatalogueInfo = defaultdict[str, set[Union[int, str]]]
CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]
@@ -118,10 +112,10 @@ def calculate_discounted_price_for_rules(
def calculate_discounted_price_for_promotions(
*,
price: Money,
- rules_info_per_promotion_id: Dict[UUID, List[PromotionRuleInfo]],
+ rules_info_per_promotion_id: dict[UUID, list[PromotionRuleInfo]],
channel: "Channel",
variant_id: Optional[int] = None,
-) -> List[Tuple[UUID, Money]]:
+) -> list[tuple[UUID, Money]]:
"""Return minimum product's price of all prices with promotions applied."""
applied_discounts = []
if rules_info_per_promotion_id:
@@ -133,10 +127,10 @@ def calculate_discounted_price_for_promotions(
def get_best_promotion_discount(
price: Money,
- rules_info_per_promotion_id: Dict[UUID, List[PromotionRuleInfo]],
+ rules_info_per_promotion_id: dict[UUID, list[PromotionRuleInfo]],
channel: "Channel",
variant_id: Optional[int] = None,
-) -> List[Tuple[UUID, Money]]:
+) -> list[tuple[UUID, Money]]:
"""Return the rules with the discount amounts for the best promotion.
The data for the promotion that gives the best saving are returned in the following
@@ -170,10 +164,10 @@ def get_best_promotion_discount(
def get_product_promotion_discounts(
*,
- rules_info: List[PromotionRuleInfo],
+ rules_info: list[PromotionRuleInfo],
channel: "Channel",
variant_id: Optional[int],
-) -> Iterator[Tuple[UUID, Callable]]:
+) -> Iterator[tuple[UUID, Callable]]:
"""Return promotion rule id, discount value for all rules applicable on product."""
for rule_info in rules_info:
try:
@@ -186,7 +180,7 @@ def get_product_discount_on_promotion(
rule_info: PromotionRuleInfo,
channel: "Channel",
variant_id: Optional[int] = None,
-) -> Tuple[UUID, Callable]:
+) -> tuple[UUID, Callable]:
"""Return rule id, discount value if rule applied or raise NotApplicable."""
if variant_id in rule_info.variant_ids and channel.id in rule_info.channel_ids:
return rule_info.rule.id, rule_info.rule.get_discount(channel.currency_code)
@@ -289,7 +283,7 @@ def create_or_update_discount_objects_from_promotion_for_checkout(
line_discounts_to_create = []
line_discounts_to_update = []
line_discount_ids_to_remove = []
- updated_fields: List[str] = []
+ updated_fields: list[str] = []
for line_info in lines_info:
line = line_info.line
@@ -381,8 +375,8 @@ def _get_discount_amount(
def _get_discounts_that_are_not_valid_anymore(
- rules_info: List["VariantPromotionRuleInfo"],
- rule_id_to_discount: Dict[int, "CheckoutLineDiscount"],
+ rules_info: list["VariantPromotionRuleInfo"],
+ rule_id_to_discount: dict[int, "CheckoutLineDiscount"],
line_info: "CheckoutLineInfo",
):
discount_ids = []
@@ -425,7 +419,7 @@ def _update_line_discount(
rule_info: "VariantPromotionRuleInfo",
rule_discount_amount: Decimal,
discount_to_update: "CheckoutLineDiscount",
- updated_fields: List[str],
+ updated_fields: list[str],
):
if discount_to_update.value_type != rule.reward_value_type:
discount_to_update.value_type = (
@@ -451,7 +445,7 @@ def _update_line_discount(
def fetch_active_promotion_rules(
variant_qs: "ProductVariantQueryset",
date: Optional[datetime.date] = None,
-) -> Dict[UUID, List[PromotionRuleInfo]]:
+) -> dict[UUID, list[PromotionRuleInfo]]:
from ..graphql.discount.utils import get_variants_for_predicate
rules_info_per_promotion_id = defaultdict(list)
diff --git a/saleor/giftcard/events.py b/saleor/giftcard/events.py
index 122f475859..23fbcdc377 100644
--- a/saleor/giftcard/events.py
+++ b/saleor/giftcard/events.py
@@ -1,4 +1,5 @@
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional
from ..account.models import User
from ..app.models import App
@@ -119,7 +120,7 @@ def gift_card_expiry_date_updated_event(
def gift_card_tags_updated_event(
gift_card: GiftCard,
- old_tags: List[str],
+ old_tags: list[str],
user: Optional[User],
app: Optional[App],
):
@@ -210,7 +211,7 @@ def gift_card_note_added_event(
def gift_cards_used_in_order_event(
- balance_data: Iterable[Tuple[GiftCard, float]],
+ balance_data: Iterable[tuple[GiftCard, float]],
order: "Order",
user: Optional[User],
app: Optional[App],
diff --git a/saleor/giftcard/search.py b/saleor/giftcard/search.py
index 9b11c099b0..21bf3b13e9 100644
--- a/saleor/giftcard/search.py
+++ b/saleor/giftcard/search.py
@@ -1,4 +1,4 @@
-from typing import List, Union
+from typing import Union
from django.contrib.postgres.search import SearchQuery
from django.db.models import Q, QuerySet, Value, prefetch_related_objects
@@ -10,14 +10,14 @@ from .models import GiftCard
GIFTCARD_FIELDS_TO_PREFETCH = ["used_by", "created_by"]
-def _add_vector(vectors: List[NoValidationSearchVector], field):
+def _add_vector(vectors: list[NoValidationSearchVector], field):
if field:
vectors += [NoValidationSearchVector(Value(field), config="simple")]
def prepare_gift_card_search_vector_value(
gift_card: GiftCard,
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
search_vectors = [NoValidationSearchVector(Value(gift_card.code), config="simple")]
_add_vector(search_vectors, gift_card.used_by_email)
_add_vector(search_vectors, gift_card.created_by_email)
@@ -33,13 +33,13 @@ def prepare_gift_card_search_vector_value(
return search_vectors
-def mark_gift_cards_search_index_as_dirty(gift_cards: Union[List[GiftCard], QuerySet]):
+def mark_gift_cards_search_index_as_dirty(gift_cards: Union[list[GiftCard], QuerySet]):
for gift_card in gift_cards:
gift_card.search_index_dirty = True
GiftCard.objects.bulk_update(gift_cards, ["search_index_dirty"])
-def mark_gift_cards_search_index_as_dirty_by_users(users: List[User]):
+def mark_gift_cards_search_index_as_dirty_by_users(users: list[User]):
emails = [user.email for user in users]
gift_cards = GiftCard.objects.filter(
Q(used_by_email__in=emails)
@@ -50,7 +50,7 @@ def mark_gift_cards_search_index_as_dirty_by_users(users: List[User]):
mark_gift_cards_search_index_as_dirty(gift_cards)
-def update_gift_cards_search_vector(gift_cards: List[GiftCard]):
+def update_gift_cards_search_vector(gift_cards: list[GiftCard]):
prefetch_related_objects(gift_cards, *GIFTCARD_FIELDS_TO_PREFETCH)
for gift_card in gift_cards:
gift_card.search_index_dirty = False
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index c29aae7767..60ff947c96 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -1,6 +1,7 @@
from collections import defaultdict
+from collections.abc import Iterable
from datetime import date
-from typing import TYPE_CHECKING, DefaultDict, Iterable, List, Optional
+from typing import TYPE_CHECKING, Optional
from uuid import UUID
from dateutil.relativedelta import relativedelta
@@ -115,8 +116,8 @@ def fulfill_gift_card_lines(
settings: "SiteSettings",
manager: "PluginsManager",
):
- lines_for_warehouses: DefaultDict[
- UUID, List[OrderFulfillmentLineInfo]
+ lines_for_warehouses: defaultdict[
+ UUID, list[OrderFulfillmentLineInfo]
] = defaultdict(list)
channel_slug = order.channel.slug
for line in gift_card_lines.prefetch_related(
diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
index f1743fe1df..2bd1b2f81e 100644
--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py
@@ -1,6 +1,5 @@
from collections import defaultdict
from copy import deepcopy
-from typing import List
import graphene
from django.core.exceptions import ValidationError
@@ -203,7 +202,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):
def clean_metadata(
cls,
field_name: str,
- metadata_list: List[dict],
+ metadata_list: list[dict],
errors_count: int,
index: int,
index_error_map: dict,
diff --git a/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py b/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py
index 24f4cc0f2b..40a2af2a99 100644
--- a/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py
+++ b/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List
from django.core.exceptions import ValidationError
@@ -52,7 +51,7 @@ class StaffBulkDelete(StaffDeleteMixin, UserBulkDelete):
@classmethod
def clean_instances(cls, info: ResolveInfo, users):
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
requestor = info.context.user
cls.check_if_users_can_be_deleted(info, users, "ids", errors)
diff --git a/saleor/graphql/account/dataloaders.py b/saleor/graphql/account/dataloaders.py
index 72d79f7eb9..b7f75733e5 100644
--- a/saleor/graphql/account/dataloaders.py
+++ b/saleor/graphql/account/dataloaders.py
@@ -1,5 +1,6 @@
from collections import defaultdict
-from typing import DefaultDict, Iterable, List, Optional, Set, Tuple, cast
+from collections.abc import Iterable
+from typing import Optional, cast
from ...account.models import Address, CustomerEvent, Group, User
from ...channel.models import Channel
@@ -39,17 +40,17 @@ class CustomerEventsByUserLoader(DataLoader):
class ThumbnailByUserIdSizeAndFormatLoader(
- DataLoader[Tuple[int, int, Optional[str]], Thumbnail]
+ DataLoader[tuple[int, int, Optional[str]], Thumbnail]
):
context_key = "thumbnail_by_user_size_and_format"
- def batch_load(self, keys: Iterable[Tuple[int, int, Optional[str]]]):
+ def batch_load(self, keys: Iterable[tuple[int, int, Optional[str]]]):
user_ids = [user_id for user_id, _, _ in keys]
thumbnails = Thumbnail.objects.using(self.database_connection_name).filter(
user_id__in=user_ids
)
- thumbnails_by_user_size_and_format_map: DefaultDict[
- Tuple[int, int, Optional[str]], Optional[Thumbnail]
+ thumbnails_by_user_size_and_format_map: defaultdict[
+ tuple[int, int, Optional[str]], Optional[Thumbnail]
] = defaultdict()
for thumbnail in thumbnails:
format = get_thumbnail_format(thumbnail.format)
@@ -92,7 +93,7 @@ class BaseAccessibleChannels(DataLoader):
self.database_connection_name
).filter(id__in=group_ids, restricted_access_to_channels=True)
- group_to_channels: DefaultDict[int, List["Channel"]] = defaultdict(list)
+ group_to_channels: defaultdict[int, list["Channel"]] = defaultdict(list)
if groups_with_channel_restriction:
group_to_channels = self.get_group_channels(
groups_with_channel_restriction.values("id"),
@@ -149,7 +150,7 @@ class AccessibleChannelsByUserIdLoader(BaseAccessibleChannels):
groups.values_list("id", flat=True)
)
- user_to_channels: DefaultDict[int, Set["Channel"]] = defaultdict(set)
+ user_to_channels: defaultdict[int, set["Channel"]] = defaultdict(set)
for user_id, group_id in user_groups.values_list("user_id", "group_id"):
user_to_channels[user_id].update(group_to_channels[group_id])
@@ -175,7 +176,7 @@ class RestrictedChannelAccessByUserIdLoader(DataLoader):
)
}
- user_to_restricted_access: DefaultDict[int, bool] = defaultdict(lambda: True)
+ user_to_restricted_access: defaultdict[int, bool] = defaultdict(lambda: True)
for user_id, group_id in user_groups.values_list("user_id", "group_id"):
user_to_restricted_access[user_id] &= group_id_to_restricted_access[
group_id
diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.py
index 1b37317cba..ec9aa6185d 100644
--- a/saleor/graphql/account/i18n.py
+++ b/saleor/graphql/account/i18n.py
@@ -1,4 +1,4 @@
-from typing import Dict, Optional
+from typing import Optional
from django.core.exceptions import ValidationError
@@ -73,7 +73,7 @@ class I18nMixin:
def attach_params_to_address_form_errors(
cls,
address_form,
- params: Dict[str, str],
+ params: dict[str, str],
values_check=True,
required_check=True,
):
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 05b52ad575..ed80f120d8 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List
from urllib.parse import urlencode
import graphene
@@ -438,7 +437,7 @@ class StaffDeleteMixin(UserDeleteMixin):
@classmethod
def clean_instance(cls, info: ResolveInfo, instance):
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
requestor = info.context.user
@@ -490,7 +489,7 @@ class StaffDeleteMixin(UserDeleteMixin):
@classmethod
def check_if_removing_left_not_manageable_permissions(
- cls, requestor, users, field, errors: defaultdict[str, List[ValidationError]]
+ cls, requestor, users, field, errors: defaultdict[str, list[ValidationError]]
):
"""Check if after removing users all permissions will be manageable.
diff --git a/saleor/graphql/account/mutations/permission_group/permission_group_create.py b/saleor/graphql/account/mutations/permission_group/permission_group_create.py
index 00b4b6351f..ba28886642 100644
--- a/saleor/graphql/account/mutations/permission_group/permission_group_create.py
+++ b/saleor/graphql/account/mutations/permission_group/permission_group_create.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import Dict, List, cast
+from typing import cast
import graphene
from django.core.exceptions import ValidationError
@@ -112,7 +112,7 @@ class PermissionGroupCreate(ModelMutation):
user = info.context.user
user = cast(User, user)
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
user_accessible_channels = get_user_accessible_channels(info, info.context.user)
cls.clean_channels(
info, instance, user_accessible_channels, errors, cleaned_input
@@ -130,7 +130,7 @@ class PermissionGroupCreate(ModelMutation):
cls,
requestor: "User",
group: models.Group,
- errors: Dict[str, List[ValidationError]],
+ errors: dict[str, list[ValidationError]],
cleaned_input: dict,
):
field = "add_permissions"
@@ -155,9 +155,9 @@ class PermissionGroupCreate(ModelMutation):
def ensure_can_manage_permissions(
cls,
requestor: "User",
- errors: Dict[str, List[ValidationError]],
+ errors: dict[str, list[ValidationError]],
field: str,
- permission_items: List[str],
+ permission_items: list[str],
):
"""Check if requestor can manage permissions from input.
@@ -186,7 +186,7 @@ class PermissionGroupCreate(ModelMutation):
@classmethod
def ensure_users_are_staff(
cls,
- errors: Dict[str, List[ValidationError]],
+ errors: dict[str, list[ValidationError]],
field: str,
cleaned_input: dict,
):
@@ -206,7 +206,7 @@ class PermissionGroupCreate(ModelMutation):
cls,
info: ResolveInfo,
group: models.Group,
- user_accessible_channels: List["Channel"],
+ user_accessible_channels: list["Channel"],
errors: dict,
cleaned_input: dict,
):
@@ -241,9 +241,9 @@ class PermissionGroupCreate(ModelMutation):
def ensure_can_manage_channels(
cls,
user: "User",
- user_accessible_channels: List["Channel"],
+ user_accessible_channels: list["Channel"],
errors: dict,
- channels: List["Channel"],
+ channels: list["Channel"],
):
# user must have access to all channels from `add_channels` list
if user.is_superuser:
@@ -265,7 +265,7 @@ class PermissionGroupCreate(ModelMutation):
@classmethod
def update_errors(
cls,
- errors: Dict[str, List[ValidationError]],
+ errors: dict[str, list[ValidationError]],
msg: str,
field: str,
code: str,
diff --git a/saleor/graphql/account/mutations/permission_group/permission_group_update.py b/saleor/graphql/account/mutations/permission_group/permission_group_update.py
index 91b4121615..6cb9e226c1 100644
--- a/saleor/graphql/account/mutations/permission_group/permission_group_update.py
+++ b/saleor/graphql/account/mutations/permission_group/permission_group_update.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import DefaultDict, Dict, List, Tuple, cast
+from typing import cast
import graphene
from django.core.exceptions import ValidationError
@@ -111,7 +111,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
requestor = info.context.user
cls.ensure_requestor_can_manage_group(info, requestor, instance)
- errors: DefaultDict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
permission_fields = ("add_permissions", "remove_permissions", "permissions")
user_fields = ("add_users", "remove_users", "users")
channel_fields = ("add_channels", "remove_channels", "channels")
@@ -151,7 +151,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
cls,
info: ResolveInfo,
group: models.Group,
- user_accessible_channels: List["Channel"],
+ user_accessible_channels: list["Channel"],
errors: dict,
cleaned_input: dict,
):
@@ -178,7 +178,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
cls,
requestor: "User",
group: models.Group,
- errors: Dict[str, List[ValidationError]],
+ errors: dict[str, list[ValidationError]],
cleaned_input: dict,
):
super().clean_permissions(requestor, group, errors, cleaned_input)
@@ -197,7 +197,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
cls,
errors: dict,
group: models.Group,
- permissions: List["str"],
+ permissions: list["str"],
):
missing_perms = get_not_manageable_permissions_after_removing_perms_from_group(
group, permissions
@@ -233,7 +233,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
def ensure_can_manage_users(
cls,
requestor: "User",
- errors: Dict[str, List[ValidationError]],
+ errors: dict[str, list[ValidationError]],
field: str,
cleaned_input: dict,
):
@@ -322,7 +322,7 @@ class PermissionGroupUpdate(PermissionGroupCreate):
cls,
errors: dict,
input_data: dict,
- fields: Tuple[str, str, str],
+ fields: tuple[str, str, str],
):
"""Check if any items are on both input field.
diff --git a/saleor/graphql/account/tests/queries/test_me.py b/saleor/graphql/account/tests/queries/test_me.py
index 698ccd7724..d012191d31 100644
--- a/saleor/graphql/account/tests/queries/test_me.py
+++ b/saleor/graphql/account/tests/queries/test_me.py
@@ -1,5 +1,6 @@
+from unittest import mock
+
import graphene
-import mock
from .....order.models import FulfillmentStatus
from .....payment.interface import (
diff --git a/saleor/graphql/account/tests/queries/test_user.py b/saleor/graphql/account/tests/queries/test_user.py
index f9534c97b3..a55379f183 100644
--- a/saleor/graphql/account/tests/queries/test_user.py
+++ b/saleor/graphql/account/tests/queries/test_user.py
@@ -1,7 +1,7 @@
+from unittest import mock
from unittest.mock import MagicMock
import graphene
-import mock
import pytest
from django.core.files import File
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 02f6f2a871..5e04cb816e 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -1,6 +1,6 @@
import uuid
from functools import partial
-from typing import List, Optional, cast
+from typing import Optional, cast
import graphene
from django.contrib.auth import get_user_model
@@ -185,7 +185,7 @@ class Address(ModelObjectType[models.Address]):
return False
@staticmethod
- def __resolve_references(roots: List["Address"], info: ResolveInfo):
+ def __resolve_references(roots: list["Address"], info: ResolveInfo):
from .resolvers import resolve_addresses
app = get_app_promise(info.context).get()
@@ -661,7 +661,7 @@ class User(ModelObjectType[models.User]):
return LanguageCodeEnum[str_to_enum(root.language_code)]
@staticmethod
- def __resolve_references(roots: List["User"], info: ResolveInfo):
+ def __resolve_references(roots: list["User"], info: ResolveInfo):
from .resolvers import resolve_users
ids = set()
@@ -945,7 +945,7 @@ class Group(ModelObjectType[models.Group]):
return AccessibleChannelsByGroupIdLoader(info.context).load(root.id)
@staticmethod
- def __resolve_references(roots: List["Group"], info: ResolveInfo):
+ def __resolve_references(roots: list["Group"], info: ResolveInfo):
from .resolvers import resolve_permission_groups
requestor = get_user_or_app_from_context(info.context)
diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.py
index be9bc03e60..4259fb20b4 100644
--- a/saleor/graphql/account/utils.py
+++ b/saleor/graphql/account/utils.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List, Optional, Set, Union
+from typing import TYPE_CHECKING, Optional, Union
from django.contrib.postgres.aggregates import ArrayAgg
from django.db.models import Q, Value
@@ -53,8 +53,8 @@ def get_user_permissions(user: "User") -> "QuerySet":
def get_out_of_scope_permissions(
- requestor: Union["User", "App", None], permissions: List[str]
-) -> List[str]:
+ requestor: Union["User", "App", None], permissions: list[str]
+) -> list[str]:
"""Return permissions that the requestor hasn't got."""
missing_permissions = []
for perm in permissions:
@@ -63,7 +63,7 @@ def get_out_of_scope_permissions(
return missing_permissions
-def get_out_of_scope_users(root_user: "User", users: List["User"]):
+def get_out_of_scope_users(root_user: "User", users: list["User"]):
"""Return users whose permission scope is wider than the given user."""
out_of_scope_users = []
for user in users:
@@ -112,7 +112,7 @@ def get_group_permission_codes(group: Group) -> "QuerySet":
).values_list("formated_codename", flat=True)
-def get_groups_which_user_can_manage(user: "User") -> List[Group]:
+def get_groups_which_user_can_manage(user: "User") -> list[Group]:
"""Return groups which user can manage."""
if not user.is_staff:
return []
@@ -122,7 +122,7 @@ def get_groups_which_user_can_manage(user: "User") -> List[Group]:
groups = Group.objects.all().annotate(group_perms=ArrayAgg("permissions"))
- editable_groups: List[Group] = []
+ editable_groups: list[Group] = []
for group in groups.iterator():
out_of_scope_permissions = set(group.group_perms) - user_permission_pks
out_of_scope_permissions.discard(None)
@@ -132,7 +132,7 @@ def get_groups_which_user_can_manage(user: "User") -> List[Group]:
return editable_groups
-def get_not_manageable_permissions_when_deactivate_or_remove_users(users: List["User"]):
+def get_not_manageable_permissions_when_deactivate_or_remove_users(users: list["User"]):
"""Return permissions that cannot be managed after deactivating or removing users.
After removing or deactivating users, for each user permission which he can manage,
@@ -177,7 +177,7 @@ def get_not_manageable_permissions_when_deactivate_or_remove_users(users: List["
def get_not_manageable_permissions_after_removing_perms_from_group(
- group: Group, permissions: List["str"]
+ group: Group, permissions: list["str"]
):
"""Return permissions that cannot be managed after removing permissions from group.
@@ -192,7 +192,7 @@ def get_not_manageable_permissions_after_removing_perms_from_group(
def get_not_manageable_permissions_after_removing_users_from_group(
- group: Group, users: List["User"]
+ group: Group, users: list["User"]
):
"""Return permissions that cannot be managed after removing users from group.
@@ -236,7 +236,7 @@ def get_not_manageable_permissions_after_group_deleting(group):
def get_not_manageable_permissions(
groups_data: dict,
- not_manageable_permissions: Set[str],
+ not_manageable_permissions: set[str],
):
# get users from groups with manage staff and look for not_manageable_permissions
# if any of not_manageable_permissions is found it is removed from set
@@ -302,7 +302,7 @@ def get_group_to_permissions_and_users_mapping():
def get_users_and_look_for_permissions_in_groups_with_manage_staff(
groups_data: dict,
- permissions_to_find: Set[str],
+ permissions_to_find: set[str],
):
"""Search for permissions in groups with manage staff and return their users.
@@ -312,7 +312,7 @@ def get_users_and_look_for_permissions_in_groups_with_manage_staff(
permissions_to_find: searched permissions
"""
- users_with_manage_staff: Set[int] = set()
+ users_with_manage_staff: set[int] = set()
for data in groups_data.values():
permissions = data["permissions"]
users = data["users"]
@@ -330,8 +330,8 @@ def get_users_and_look_for_permissions_in_groups_with_manage_staff(
def look_for_permission_in_users_with_manage_staff(
groups_data: dict,
- users_to_check: Set[int],
- permissions_to_find: Set[str],
+ users_to_check: set[int],
+ permissions_to_find: set[str],
):
"""Search for permissions in user with manage staff groups.
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index c3efe9dc19..eb0efe0feb 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -1,5 +1,5 @@
import base64
-from typing import List, Optional, Type, Union
+from typing import Optional, Union
import graphene
@@ -326,7 +326,7 @@ class AppBrandLogo(BaseObjectType):
if isinstance(root, models.App):
object_type = "App"
- dataloader: Type[DataLoader] = ThumbnailByAppIdSizeAndFormatLoader
+ dataloader: type[DataLoader] = ThumbnailByAppIdSizeAndFormatLoader
elif isinstance(root, models.AppInstallation):
object_type = "AppInstallation"
dataloader = ThumbnailByAppInstallationIdSizeAndFormatLoader
@@ -587,7 +587,7 @@ class App(ModelObjectType[models.App]):
return AppExtensionByAppIdLoader(info.context).load(root.id)
@staticmethod
- def __resolve_references(roots: List["App"], info: ResolveInfo):
+ def __resolve_references(roots: list["App"], info: ResolveInfo):
from .resolvers import resolve_apps
requestor = get_user_or_app_from_context(info.context)
diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_create.py b/saleor/graphql/attribute/mutations/attribute_bulk_create.py
index 4d08f1c362..cb992367c6 100644
--- a/saleor/graphql/attribute/mutations/attribute_bulk_create.py
+++ b/saleor/graphql/attribute/mutations/attribute_bulk_create.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import List, Tuple, Union
+from typing import Union
import graphene
from django.core.exceptions import ValidationError
@@ -233,8 +233,8 @@ class AttributeBulkCreate(BaseMutation):
def clean_attributes(
cls,
info: ResolveInfo,
- attributes_data: List[AttributeCreateInput],
- index_error_map: dict[int, List[AttributeBulkCreateError]],
+ attributes_data: list[AttributeCreateInput],
+ index_error_map: dict[int, list[AttributeBulkCreateError]],
):
cleaned_inputs_map: dict = {}
@@ -335,7 +335,7 @@ class AttributeBulkCreate(BaseMutation):
existing_slugs: set,
values_existing_external_refs: set,
duplicated_values_external_ref: set,
- index_error_map: dict[int, List[AttributeBulkCreateError]],
+ index_error_map: dict[int, list[AttributeBulkCreateError]],
):
values = attribute_data.pop("values", None)
cleaned_input = ModelMutation.clean_input(
@@ -343,7 +343,7 @@ class AttributeBulkCreate(BaseMutation):
)
# check permissions based on attribute type
- permissions: Union[Tuple[ProductTypePermissions], Tuple[PageTypePermissions]]
+ permissions: Union[tuple[ProductTypePermissions], tuple[PageTypePermissions]]
if cleaned_input["type"] == AttributeTypeEnum.PRODUCT_TYPE.value:
permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
else:
@@ -425,9 +425,9 @@ class AttributeBulkCreate(BaseMutation):
info: ResolveInfo,
cleaned_inputs_map: dict[int, dict],
error_policy: str,
- index_error_map: dict[int, List[AttributeBulkCreateError]],
- ) -> List[dict]:
- instances_data_and_errors_list: List[dict] = []
+ index_error_map: dict[int, list[AttributeBulkCreateError]],
+ ) -> list[dict]:
+ instances_data_and_errors_list: list[dict] = []
for index, cleaned_input in cleaned_inputs_map.items():
if not cleaned_input:
@@ -483,7 +483,7 @@ class AttributeBulkCreate(BaseMutation):
values_data: list[AttributeValueCreateInput],
values: list[models.AttributeValue],
attr_index: int,
- index_error_map: dict[int, List[AttributeBulkCreateError]],
+ index_error_map: dict[int, list[AttributeBulkCreateError]],
):
for value_index, value_data in enumerate(values_data):
value = models.AttributeValue(attribute=attribute)
diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_update.py b/saleor/graphql/attribute/mutations/attribute_bulk_update.py
index df956e2a4e..b2754ec340 100644
--- a/saleor/graphql/attribute/mutations/attribute_bulk_update.py
+++ b/saleor/graphql/attribute/mutations/attribute_bulk_update.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import List, Tuple, Union
+from typing import Union
import graphene
from django.core.exceptions import ValidationError
@@ -125,8 +125,8 @@ class AttributeBulkUpdate(BaseMutation):
def clean_attributes(
cls,
info: ResolveInfo,
- attributes_data: List[AttributeBulkUpdateInput],
- index_error_map: dict[int, List[AttributeBulkUpdateError]],
+ attributes_data: list[AttributeBulkUpdateInput],
+ index_error_map: dict[int, list[AttributeBulkUpdateError]],
):
cleaned_inputs_map: dict = {}
@@ -235,7 +235,7 @@ class AttributeBulkUpdate(BaseMutation):
@classmethod
def _get_attrs_existing_and_duplicated_external_refs(
- cls, attributes_data: List[AttributeBulkUpdateInput]
+ cls, attributes_data: list[AttributeBulkUpdateInput]
):
attr_input_external_refs = [
attribute_data.fields.external_reference
@@ -252,7 +252,7 @@ class AttributeBulkUpdate(BaseMutation):
return attrs_existing_external_refs, duplicated_external_ref
@classmethod
- def _get_attrs_existing_slugs(cls, attributes_data: List[AttributeBulkUpdateInput]):
+ def _get_attrs_existing_slugs(cls, attributes_data: list[AttributeBulkUpdateInput]):
return set(
models.Attribute.objects.filter(
slug__in=[
@@ -265,7 +265,7 @@ class AttributeBulkUpdate(BaseMutation):
@classmethod
def _get_values_existing_and_duplicated_external_refs(
- cls, attributes_data: List[AttributeBulkUpdateInput]
+ cls, attributes_data: list[AttributeBulkUpdateInput]
):
values_input_external_refs = [
value.external_reference
@@ -295,7 +295,7 @@ class AttributeBulkUpdate(BaseMutation):
values_existing_external_refs,
duplicated_values_external_ref,
attributes,
- index_error_map: dict[int, List[AttributeBulkUpdateError]],
+ index_error_map: dict[int, list[AttributeBulkUpdateError]],
):
remove_values = attribute_data.fields.pop("remove_values", [])
add_values = attribute_data.fields.pop("add_values", [])
@@ -314,7 +314,7 @@ class AttributeBulkUpdate(BaseMutation):
attribute_data["instance"] = attr
# check permissions based on attribute type
- permissions: Union[Tuple[ProductTypePermissions], Tuple[PageTypePermissions]]
+ permissions: Union[tuple[ProductTypePermissions], tuple[PageTypePermissions]]
if attr.type == AttributeTypeEnum.PRODUCT_TYPE.value:
permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
else:
@@ -402,9 +402,9 @@ class AttributeBulkUpdate(BaseMutation):
info: ResolveInfo,
cleaned_inputs_map: dict[int, dict],
error_policy: str,
- index_error_map: dict[int, List[AttributeBulkUpdateError]],
- ) -> List[dict]:
- instances_data_and_errors_list: List[dict] = []
+ index_error_map: dict[int, list[AttributeBulkUpdateError]],
+ ) -> list[dict]:
+ instances_data_and_errors_list: list[dict] = []
for index, cleaned_input in cleaned_inputs_map.items():
if not cleaned_input:
@@ -489,7 +489,7 @@ class AttributeBulkUpdate(BaseMutation):
@classmethod
def get_attributes(
- cls, attributes_data: List[AttributeBulkUpdateInput]
+ cls, attributes_data: list[AttributeBulkUpdateInput]
) -> list[models.Attribute]:
lookup = Q()
diff --git a/saleor/graphql/attribute/mutations/attribute_create.py b/saleor/graphql/attribute/mutations/attribute_create.py
index 54269c91cb..8fc1474f10 100644
--- a/saleor/graphql/attribute/mutations/attribute_create.py
+++ b/saleor/graphql/attribute/mutations/attribute_create.py
@@ -1,4 +1,4 @@
-from typing import Tuple, Union
+from typing import Union
import graphene
from django.core.exceptions import ValidationError
@@ -152,7 +152,7 @@ class AttributeCreate(AttributeMixin, ModelMutation):
cls, _root, info: ResolveInfo, /, *, input
):
# check permissions based on attribute type
- permissions: Union[Tuple[ProductTypePermissions], Tuple[PageTypePermissions]]
+ permissions: Union[tuple[ProductTypePermissions], tuple[PageTypePermissions]]
if input["type"] == AttributeTypeEnum.PRODUCT_TYPE.value:
permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
else:
diff --git a/saleor/graphql/attribute/mutations/attribute_value_create.py b/saleor/graphql/attribute/mutations/attribute_value_create.py
index 2f6dbb4917..df7759ac53 100644
--- a/saleor/graphql/attribute/mutations/attribute_value_create.py
+++ b/saleor/graphql/attribute/mutations/attribute_value_create.py
@@ -1,5 +1,3 @@
-from typing import Dict, List
-
import graphene
from django.core.exceptions import ValidationError
@@ -65,7 +63,7 @@ class AttributeValueCreate(AttributeMixin, ModelMutation):
input_type = instance.attribute.input_type
is_swatch_attr = input_type == AttributeInputType.SWATCH
- errors: Dict[str, List[ValidationError]] = {}
+ errors: dict[str, list[ValidationError]] = {}
if not is_swatch_attr:
for field in cls.ONLY_SWATCH_FIELDS:
if cleaned_input.get(field):
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index 06922614a8..445ef6e205 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -1,8 +1,9 @@
import datetime
import re
from collections import defaultdict, namedtuple
+from collections.abc import Iterable
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Type, Union
+from typing import TYPE_CHECKING, Optional, Union
import graphene
from django.core.exceptions import ValidationError
@@ -49,12 +50,12 @@ class AttrValuesForSelectableFieldInput:
class AttrValuesInput:
global_id: Optional[str] = None
external_reference: Optional[str] = None
- values: Optional[List[str]] = None
+ values: Optional[list[str]] = None
dropdown: Optional[AttrValuesForSelectableFieldInput] = None
swatch: Optional[AttrValuesForSelectableFieldInput] = None
- multiselect: Optional[List[AttrValuesForSelectableFieldInput]] = None
+ multiselect: Optional[list[AttrValuesForSelectableFieldInput]] = None
numeric: Optional[str] = None
- references: Union[List[str], List[page_models.Page], None] = None
+ references: Union[list[str], list[page_models.Page], None] = None
file_url: Optional[str] = None
content_type: Optional[str] = None
rich_text: Optional[dict] = None
@@ -67,8 +68,8 @@ class AttrValuesInput:
T_INSTANCE = Union[
product_models.Product, product_models.ProductVariant, page_models.Page
]
-T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]
-T_ERROR_DICT = Dict[Tuple[str, str], List]
+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"])
@@ -110,14 +111,14 @@ class AttributeAssignmentMixin:
qs: "QuerySet",
error_class,
*,
- global_ids: List[str],
+ global_ids: list[str],
external_references: Iterable[str],
pks: Iterable[int],
):
"""Retrieve attributes nodes from given global IDs or external reference."""
qs = qs.filter(Q(pk__in=pks) | Q(external_reference__in=external_references))
- nodes: List[attribute_models.Attribute] = list(qs)
+ nodes: list[attribute_models.Attribute] = list(qs)
if not nodes:
raise ValidationError(
@@ -223,7 +224,7 @@ class AttributeAssignmentMixin:
:raises ValidationError: contain the message.
:return: The resolved data
"""
- error_class: Union[Type[PageErrorCode], Type[ProductErrorCode]] = (
+ error_class: Union[type[PageErrorCode], type[ProductErrorCode]] = (
PageErrorCode if is_page_attributes else ProductErrorCode
)
@@ -515,7 +516,7 @@ class AttributeAssignmentMixin:
if not attr_values_input.multiselect:
return tuple()
- attribute_values: List[attribute_models.AttributeValue] = []
+ attribute_values: list[attribute_models.AttributeValue] = []
for attr_value in attr_values_input.multiselect:
external_ref = attr_value.external_reference
@@ -761,7 +762,7 @@ def get_variant_selection_attributes(qs: "QuerySet") -> "QuerySet":
)
-def prepare_attribute_values(attribute: attribute_models.Attribute, values: List[str]):
+def prepare_attribute_values(attribute: attribute_models.Attribute, values: list[str]):
slug_to_value_map = {}
name_to_value_map = {}
for val in attribute.values.filter(Q(name__in=values) | Q(slug__in=values)):
@@ -797,7 +798,7 @@ def prepare_attribute_values(attribute: attribute_models.Attribute, values: List
return result
-def get_existing_slugs(attribute: attribute_models.Attribute, values: List[str]):
+def get_existing_slugs(attribute: attribute_models.Attribute, values: list[str]):
lookup = Q()
for value in values:
lookup |= Q(slug__startswith=slugify(unidecode(value)))
@@ -870,7 +871,7 @@ class AttributeInputErrors:
def validate_attributes_input(
- input_data: List[Tuple["Attribute", "AttrValuesInput"]],
+ input_data: list[tuple["Attribute", "AttrValuesInput"]],
attribute_qs: "QuerySet",
*,
is_page_attributes: bool,
@@ -1302,9 +1303,9 @@ def validate_values(
def validate_required_attributes(
- input_data: List[Tuple["Attribute", "AttrValuesInput"]],
+ input_data: list[tuple["Attribute", "AttrValuesInput"]],
attribute_qs: "QuerySet",
- errors: List[ValidationError],
+ errors: list[ValidationError],
error_code_enum,
):
"""Ensure all required attributes are supplied."""
diff --git a/saleor/graphql/channel/filters.py b/saleor/graphql/channel/filters.py
index 9a2b343098..25fe3ae2fa 100644
--- a/saleor/graphql/channel/filters.py
+++ b/saleor/graphql/channel/filters.py
@@ -1,6 +1,3 @@
-from typing import Dict
-
-
-def get_channel_slug_from_filter_data(filter_data: Dict):
+def get_channel_slug_from_filter_data(filter_data: dict):
channel = filter_data.get("channel")
return str(channel) if channel else None
diff --git a/saleor/graphql/channel/mutations/base_channel_listing.py b/saleor/graphql/channel/mutations/base_channel_listing.py
index de022ef3b7..ac29e81939 100644
--- a/saleor/graphql/channel/mutations/base_channel_listing.py
+++ b/saleor/graphql/channel/mutations/base_channel_listing.py
@@ -1,5 +1,6 @@
import datetime
-from typing import DefaultDict, Dict, Iterable, List
+from collections import defaultdict
+from collections.abc import Iterable
import pytz
from django.core.exceptions import ValidationError
@@ -11,7 +12,7 @@ from ...core.mutations import BaseMutation
from ...core.utils import get_duplicated_values, get_duplicates_items
from ..types import Channel
-ErrorType = DefaultDict[str, List[ValidationError]]
+ErrorType = defaultdict[str, list[ValidationError]]
class BaseChannelListingMutation(BaseMutation):
@@ -64,7 +65,7 @@ class BaseChannelListingMutation(BaseMutation):
errors: ErrorType,
error_code,
input_source="add_channels",
- ) -> Dict:
+ ) -> dict:
add_channels = input.get(input_source, [])
add_channels_ids = [channel["channel_id"] for channel in add_channels]
remove_channels_ids = input.get("remove_channels", [])
@@ -79,7 +80,7 @@ class BaseChannelListingMutation(BaseMutation):
)
if errors:
return {}
- channels_to_add: List["models.Channel"] = []
+ channels_to_add: list["models.Channel"] = []
if add_channels_ids:
channels_to_add = cls.get_nodes_or_error(
add_channels_ids, "channel_id", Channel
diff --git a/saleor/graphql/channel/mutations/channel_delete.py b/saleor/graphql/channel/mutations/channel_delete.py
index b2820f863c..1c94c3e64d 100644
--- a/saleor/graphql/channel/mutations/channel_delete.py
+++ b/saleor/graphql/channel/mutations/channel_delete.py
@@ -1,4 +1,4 @@
-from typing import Dict, Optional
+from typing import Optional
import graphene
from django.core.exceptions import ValidationError
@@ -121,7 +121,7 @@ class ChannelDelete(ModelDeleteMutation):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, root, info: ResolveInfo, /, *, id: str, input: Optional[Dict] = None
+ cls, root, info: ResolveInfo, /, *, id: str, input: Optional[dict] = None
):
origin_channel = cls.get_node_or_error(info, id, only_type=Channel)
target_channel_global_id = input.get("channel_id") if input else None
diff --git a/saleor/graphql/channel/mutations/channel_reorder_warehouses.py b/saleor/graphql/channel/mutations/channel_reorder_warehouses.py
index 3394032c84..e6877f07d2 100644
--- a/saleor/graphql/channel/mutations/channel_reorder_warehouses.py
+++ b/saleor/graphql/channel/mutations/channel_reorder_warehouses.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import DefaultDict
import graphene
from django.core.exceptions import ValidationError
@@ -90,7 +89,7 @@ class ChannelReorderWarehouses(BaseMutation):
str(warehouse_data["warehouse_id"]): warehouse_data["id"]
for warehouse_data in warehouses_m2m.values("id", "warehouse_id")
}
- operations: DefaultDict[str, int] = defaultdict(int)
+ operations: defaultdict[str, int] = defaultdict(int)
for warehouse_pk, move in zip(warehouse_pks, moves):
warehouse_m2m_id = warehouse_id_to_warehouse_m2m_id[warehouse_pk]
operations[warehouse_m2m_id] += move.sort_order
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 88c82216e5..1d5cadadc9 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -1,6 +1,6 @@
import collections
import itertools
-from typing import TYPE_CHECKING, Dict, List, Type, TypeVar, Union, cast
+from typing import TYPE_CHECKING, TypeVar, Union, cast
import graphene
from django.db.models import Model
@@ -104,7 +104,7 @@ class ChannelContextType(ChannelContextTypeForObjectType[T]):
if cls._meta.model._meta.proxy:
model = root._meta.model
else:
- model = cast(Type[Model], root._meta.model._meta.concrete_model)
+ model = cast(type[Model], root._meta.model._meta.concrete_model)
return model == cls._meta.model
@@ -469,7 +469,7 @@ class Channel(ModelObjectType):
shipping_zones_loader = ShippingZonesByChannelIdLoader(info.context).load(
root.id
)
- shipping_zone_countries: Dict[int, List[Country]] = collections.defaultdict(
+ shipping_zone_countries: dict[int, list[Country]] = collections.defaultdict(
list
)
requested_countries = data.get("countries", [])
@@ -527,7 +527,7 @@ class Channel(ModelObjectType):
_group_shipping_methods_by_country
)
- def get_shipping_methods(shipping_zones: List["ShippingZone"]):
+ def get_shipping_methods(shipping_zones: list["ShippingZone"]):
shipping_zones_keys = [shipping_zone.id for shipping_zone in shipping_zones]
for shipping_zone in shipping_zones:
shipping_zone_countries[shipping_zone.id] = shipping_zone.countries
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
index 4769e92f65..2eeba3638d 100644
--- a/saleor/graphql/checkout/dataloaders.py
+++ b/saleor/graphql/checkout/dataloaders.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import Iterable, List, Tuple
+from collections.abc import Iterable
from django.db.models import F
from promise import Promise
@@ -70,7 +70,7 @@ class CheckoutByTokenLoader(DataLoader[str, Checkout]):
return [checkouts.get(token) for token in keys]
-class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, List[CheckoutLineInfo]]):
+class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, list[CheckoutLineInfo]]):
context_key = "checkoutlinesinfo_by_checkout"
def batch_load(self, keys):
@@ -222,7 +222,7 @@ class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, List[CheckoutLineIn
return Promise.all([checkouts, checkout_lines]).then(with_checkout_lines)
-class CheckoutByUserLoader(DataLoader[int, List[Checkout]]):
+class CheckoutByUserLoader(DataLoader[int, list[Checkout]]):
context_key = "checkout_by_user"
def batch_load(self, keys):
@@ -235,10 +235,10 @@ class CheckoutByUserLoader(DataLoader[int, List[Checkout]]):
return [checkout_by_user_map[user_id] for user_id in keys]
-class CheckoutByUserAndChannelLoader(DataLoader[Tuple[int, str], List[Checkout]]):
+class CheckoutByUserAndChannelLoader(DataLoader[tuple[int, str], list[Checkout]]):
context_key = "checkout_by_user_and_channel"
- def batch_load(self, keys: Iterable[Tuple[int, str]]):
+ def batch_load(self, keys: Iterable[tuple[int, str]]):
user_ids = [key[0] for key in keys]
channel_slugs = [key[1] for key in keys]
checkouts = (
@@ -274,8 +274,8 @@ class VariantPromotionRuleInfoByCheckoutLineIdLoader(DataLoader):
def with_channel_listing_promotion_rules(
variant_listing_promotion_rules,
):
- rule_ids: List[int] = []
- rule_ids_language_codes: List[Tuple[int, str]] = []
+ rule_ids: list[int] = []
+ rule_ids_language_codes: list[tuple[int, str]] = []
for listing_promotion_rules, language_code in zip(
variant_listing_promotion_rules, language_codes
):
@@ -589,7 +589,7 @@ class CheckoutLineByIdLoader(DataLoader[str, CheckoutLine]):
return [checkout_lines.get(line_id) for line_id in keys]
-class CheckoutLinesByCheckoutTokenLoader(DataLoader[str, List[CheckoutLine]]):
+class CheckoutLinesByCheckoutTokenLoader(DataLoader[str, list[CheckoutLine]]):
context_key = "checkoutlines_by_checkout"
def batch_load(self, keys):
@@ -602,7 +602,7 @@ class CheckoutLinesByCheckoutTokenLoader(DataLoader[str, List[CheckoutLine]]):
return [line_map.get(checkout_id, []) for checkout_id in keys]
-class TransactionItemsByCheckoutIDLoader(DataLoader[str, List[TransactionItem]]):
+class TransactionItemsByCheckoutIDLoader(DataLoader[str, list[TransactionItem]]):
context_key = "transaction_items_by_checkout_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index 76f9d3b0ac..2afe632dba 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -1,4 +1,4 @@
-from typing import Iterable
+from collections.abc import Iterable
import graphene
from django.core.exceptions import ValidationError
diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.py
index 6a1207f365..a793539a73 100644
--- a/saleor/graphql/checkout/mutations/checkout_create.py
+++ b/saleor/graphql/checkout/mutations/checkout_create.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
import graphene
from django.conf import settings
@@ -198,7 +198,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
@classmethod
def clean_checkout_lines(
cls, info: ResolveInfo, lines, country, channel
- ) -> Tuple[List[product_models.ProductVariant], List["CheckoutLineData"]]:
+ ) -> tuple[list[product_models.ProductVariant], list["CheckoutLineData"]]:
app = get_app_promise(info.context).get()
site = get_site_promise(info.context).get()
check_permissions_for_custom_prices(app, lines)
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index 60fa1bd96a..8e4d1f3beb 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -1,4 +1,5 @@
-from typing import Iterable, Optional
+from collections.abc import Iterable
+from typing import Optional
import graphene
from django.core.exceptions import ValidationError
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index 58e1c0030c..605aadb81f 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -1,5 +1,3 @@
-from typing import Dict, List
-
import graphene
from ....checkout.error_codes import CheckoutErrorCode
@@ -222,7 +220,7 @@ class CheckoutLinesAdd(BaseMutation):
return CheckoutLinesAdd(checkout=checkout)
@classmethod
- def _get_variants_from_lines_input(cls, lines: List[Dict]) -> List[ProductVariant]:
+ def _get_variants_from_lines_input(cls, lines: list[dict]) -> list[ProductVariant]:
"""Return list of ProductVariant objects.
Uses variants ids provided in CheckoutLineInput to fetch ProductVariant objects.
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.py
index 0371e39469..8a3bafb6ee 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py
@@ -1,5 +1,3 @@
-from typing import Dict, List
-
import graphene
from django.forms import ValidationError
@@ -194,7 +192,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
)
@classmethod
- def _get_variants_from_lines_input(cls, lines: List[Dict]) -> List[ProductVariant]:
+ def _get_variants_from_lines_input(cls, lines: list[dict]) -> list[ProductVariant]:
"""Return list of ProductVariant objects.
Uses variants ids or lines ids provided in CheckoutLineUpdateInput to
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
index 422a4d8bf0..957832936d 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
@@ -1,4 +1,5 @@
-from typing import TYPE_CHECKING, Iterable
+from collections.abc import Iterable
+from typing import TYPE_CHECKING
import graphene
from django.core.exceptions import ValidationError
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index ef6f645741..252e7a551d 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -1,17 +1,13 @@
import datetime
import uuid
from collections import defaultdict
+from collections.abc import Iterable
from dataclasses import dataclass
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
- DefaultDict,
- Dict,
- Iterable,
- List,
Optional,
- Type,
Union,
cast,
)
@@ -111,12 +107,12 @@ def update_checkout_shipping_method_if_invalid(
def get_variants_and_total_quantities(
- variants: List[ProductVariant],
+ variants: list[ProductVariant],
lines_data: Iterable[CheckoutLineData],
quantity_to_update_check=False,
):
- variants_total_quantity_map: DefaultDict[ProductVariant, int] = defaultdict(int)
- mapped_data: DefaultDict[Optional[str], int] = defaultdict(int)
+ variants_total_quantity_map: defaultdict[ProductVariant, int] = defaultdict(int)
+ mapped_data: defaultdict[Optional[str], int] = defaultdict(int)
if quantity_to_update_check:
lines_data = filter(lambda d: d.quantity_to_update, lines_data)
@@ -296,7 +292,7 @@ def get_checkout_by_token(
def get_checkout(
- mutation_class: Type["BaseMutation"],
+ mutation_class: type["BaseMutation"],
info: ResolveInfo,
checkout_id: Optional[str] = None,
token: Optional[uuid.UUID] = None,
@@ -338,15 +334,15 @@ def get_checkout(
def group_lines_input_on_add(
- lines: List[Dict[str, Any]], existing_lines_info=None
-) -> List[CheckoutLineData]:
+ lines: list[dict[str, Any]], existing_lines_info=None
+) -> list[CheckoutLineData]:
"""Return list od CheckoutLineData objects.
Lines data provided in CheckoutLineInput will be grouped depending on
provided parameters.
"""
- grouped_checkout_lines_data: List[CheckoutLineData] = []
- checkout_lines_data_map: Dict[str, CheckoutLineData] = defaultdict(CheckoutLineData)
+ grouped_checkout_lines_data: list[CheckoutLineData] = []
+ checkout_lines_data_map: dict[str, CheckoutLineData] = defaultdict(CheckoutLineData)
for line in lines:
variant_id = cast(str, line.get("variant_id"))
@@ -404,16 +400,16 @@ def group_lines_input_on_add(
def group_lines_input_data_on_update(
- lines: List[Dict[str, Any]], existing_lines_info=None
-) -> List[CheckoutLineData]:
+ lines: list[dict[str, Any]], existing_lines_info=None
+) -> list[CheckoutLineData]:
"""Return list od CheckoutLineData objects.
This function is used in CheckoutLinesUpdate mutation.
Lines data provided in CheckoutLineUpdateInput will be grouped depending on
provided parameters.
"""
- grouped_checkout_lines_data: List[CheckoutLineData] = []
- checkout_lines_data_map: Dict[str, CheckoutLineData] = defaultdict(CheckoutLineData)
+ grouped_checkout_lines_data: list[CheckoutLineData] = []
+ checkout_lines_data_map: dict[str, CheckoutLineData] = defaultdict(CheckoutLineData)
for line in lines:
variant_id = cast(str, line.get("variant_id"))
@@ -463,7 +459,7 @@ def check_permissions_for_custom_prices(app, lines):
def find_line_id_when_variant_parameter_used(
- variant_db_id: str, lines_info: List[CheckoutLineInfo]
+ variant_db_id: str, lines_info: list[CheckoutLineInfo]
):
"""Return line id when variantId parameter was used.
@@ -498,7 +494,7 @@ def find_line_id_when_variant_parameter_used(
def find_variant_id_when_line_parameter_used(
- line_db_id: str, lines_info: List[CheckoutLineInfo]
+ line_db_id: str, lines_info: list[CheckoutLineInfo]
):
"""Return variant id when lineId parameter was used."""
if not lines_info:
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index d971842a26..81654c5f20 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -804,7 +804,7 @@ def test_checkout_add_variant_voucher_code_apply_once_per_order(
lines = checkout.lines.all()
checkout.lines.last().delete()
- variant_1, variant_2, variant_3 = [line.variant for line in lines]
+ variant_1, variant_2, variant_3 = (line.variant for line in lines)
variant_1_listing = variant_1.channel_listings.get(channel=channel)
variant_2_listing = variant_2.channel_listings.get(channel=channel)
variant_3_listing = variant_3.channel_listings.get(channel=channel)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index ad18101ff8..c0cfa7ad5e 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -177,7 +177,7 @@ class CheckoutLineProblem(graphene.Union):
return CheckoutLineProblemInsufficientStock
if isinstance(instance, problems.CheckoutLineProblemVariantNotAvailable):
return CheckoutLineProblemVariantNotAvailable
- return super(CheckoutLineProblem, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
class CheckoutProblem(graphene.Union):
@@ -196,7 +196,7 @@ class CheckoutProblem(graphene.Union):
return CheckoutLineProblemInsufficientStock
if isinstance(instance, problems.CheckoutLineProblemVariantNotAvailable):
return CheckoutLineProblemVariantNotAvailable
- return super(CheckoutProblem, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
class CheckoutLine(ModelObjectType[models.CheckoutLine]):
@@ -460,7 +460,7 @@ class DeliveryMethod(graphene.Union):
if isinstance(instance, warehouse_models.Warehouse):
return Warehouse
- return super(DeliveryMethod, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
class Checkout(ModelObjectType[models.Checkout]):
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index 95667a63bd..0bdf4e2ff0 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -1,14 +1,11 @@
import json
+from collections.abc import Iterable
from decimal import Decimal, InvalidOperation
from typing import (
TYPE_CHECKING,
Any,
Callable,
- Dict,
- Iterable,
- List,
Optional,
- Tuple,
Union,
)
@@ -33,7 +30,7 @@ from ..utils.sorting import sort_queryset_for_connection
if TYPE_CHECKING:
from ..core import ResolveInfo
-ConnectionArguments = Dict[str, Any]
+ConnectionArguments = dict[str, Any]
EPSILON = Decimal("0.000001")
FILTERS_NAME = "_FILTERS_NAME"
@@ -49,7 +46,7 @@ def to_global_cursor(values):
return base64(json.dumps(values))
-def from_global_cursor(cursor) -> List[str]:
+def from_global_cursor(cursor) -> list[str]:
values = unbase64(cursor)
return json.loads(values)
@@ -67,7 +64,7 @@ def get_field_value(instance: DjangoModel, field_name: str):
def _prepare_filter_by_rank_expression(
- cursor: List[str],
+ cursor: list[str],
sorting_direction: str,
coerce_id: Callable[[str], Any],
) -> Q:
@@ -94,11 +91,11 @@ def _prepare_filter_by_rank_expression(
def _prepare_filter_expression(
field_name: str,
index: int,
- cursor: List[str],
- sorting_fields: List[str],
+ cursor: list[str],
+ sorting_fields: list[str],
sorting_direction: str,
-) -> Tuple[Q, Dict[str, Union[str, bool]]]:
- field_expression: Dict[str, Union[str, bool]] = {}
+) -> tuple[Q, dict[str, Union[str, bool]]]:
+ field_expression: dict[str, Union[str, bool]] = {}
extra_expression = Q()
for cursor_id, cursor_value in enumerate(cursor[:index]):
field_expression[sorting_fields[cursor_id]] = cursor_value
@@ -115,8 +112,8 @@ def _prepare_filter_expression(
def _prepare_filter(
- cursor: List[str],
- sorting_fields: List[str],
+ cursor: list[str],
+ sorting_fields: list[str],
sorting_direction: str,
coerce_id: Callable[[str], Any],
) -> Q:
@@ -577,7 +574,7 @@ def where_filter_qs(iterable, args, filterset_class, filter_input, request):
return queryset
-def contains_filter_operator(input: Dict[str, Union[dict, str]]):
+def contains_filter_operator(input: dict[str, Union[dict, str]]):
return any([operator in input for operator in ["AND", "OR", "NOT"]])
diff --git a/saleor/graphql/core/context.py b/saleor/graphql/core/context.py
index 0afb3974d6..b98ba6e030 100644
--- a/saleor/graphql/core/context.py
+++ b/saleor/graphql/core/context.py
@@ -1,5 +1,5 @@
import datetime
-from typing import TYPE_CHECKING, Any, Dict, Optional, Union
+from typing import TYPE_CHECKING, Any, Optional, Union
from django.conf import settings
from django.http import HttpRequest
@@ -14,9 +14,9 @@ if TYPE_CHECKING:
class SaleorContext(HttpRequest):
_cached_user: Optional[User]
- decoded_auth_token: Optional[Dict[str, Any]]
+ decoded_auth_token: Optional[dict[str, Any]]
allow_replica: bool = True
- dataloaders: Dict[str, "DataLoader"]
+ dataloaders: dict[str, "DataLoader"]
app: Optional[App]
user: Optional[User] # type: ignore[assignment]
requestor: Union[App, User, None]
diff --git a/saleor/graphql/core/dataloaders.py b/saleor/graphql/core/dataloaders.py
index b38877ba34..48b464f87e 100644
--- a/saleor/graphql/core/dataloaders.py
+++ b/saleor/graphql/core/dataloaders.py
@@ -1,5 +1,6 @@
from collections import defaultdict
-from typing import DefaultDict, Generic, Iterable, List, Optional, Tuple, TypeVar, Union
+from collections.abc import Iterable
+from typing import Generic, Optional, TypeVar, Union
import opentracing
import opentracing.tags
@@ -23,7 +24,7 @@ class DataLoader(BaseLoader, Generic[K, R]):
def __new__(cls, context: SaleorContext):
key = cls.context_key
if key is None:
- raise TypeError("Data loader %r does not define a context key" % (cls,))
+ raise TypeError(f"Data loader {cls} does not define a context key")
if not hasattr(context, "dataloaders"):
context.dataloaders = {}
if key not in context.dataloaders:
@@ -40,7 +41,7 @@ class DataLoader(BaseLoader, Generic[K, R]):
def batch_load_fn( # pylint: disable=method-hidden
self, keys: Iterable[K]
- ) -> Promise[List[R]]:
+ ) -> Promise[list[R]]:
with opentracing.global_tracer().start_active_span(
self.__class__.__name__
) as scope:
@@ -51,24 +52,24 @@ class DataLoader(BaseLoader, Generic[K, R]):
return Promise.resolve(results)
return results
- def batch_load(self, keys: Iterable[K]) -> Union[Promise[List[R]], List[R]]:
+ def batch_load(self, keys: Iterable[K]) -> Union[Promise[list[R]], list[R]]:
raise NotImplementedError()
class BaseThumbnailBySizeAndFormatLoader(
- DataLoader[Tuple[int, int, Optional[str]], Thumbnail]
+ DataLoader[tuple[int, int, Optional[str]], Thumbnail]
):
model_name: str
- def batch_load(self, keys: Iterable[Tuple[int, int, Optional[str]]]):
+ def batch_load(self, keys: Iterable[tuple[int, int, Optional[str]]]):
model_name = self.model_name.lower()
instance_ids = [id for id, _, _ in keys]
lookup = {f"{model_name}_id__in": instance_ids}
thumbnails = Thumbnail.objects.using(self.database_connection_name).filter(
**lookup
)
- thumbnails_by_instance_id_size_and_format_map: DefaultDict[
- Tuple[int, int, Optional[str]], Thumbnail
+ thumbnails_by_instance_id_size_and_format_map: defaultdict[
+ tuple[int, int, Optional[str]], Thumbnail
] = defaultdict()
for thumbnail in thumbnails:
format = get_thumbnail_format(thumbnail.format)
diff --git a/saleor/graphql/core/federation/entities.py b/saleor/graphql/core/federation/entities.py
index 08dd1dac23..6dbb7e449c 100644
--- a/saleor/graphql/core/federation/entities.py
+++ b/saleor/graphql/core/federation/entities.py
@@ -1,8 +1,8 @@
-from typing import Dict, TypeVar
+from typing import TypeVar
import graphene
-federated_entities: Dict[str, graphene.ObjectType] = {}
+federated_entities: dict[str, graphene.ObjectType] = {}
T = TypeVar("T", bound=graphene.ObjectType)
diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.py
index 93f8779ebb..a31e83be96 100644
--- a/saleor/graphql/core/fields.py
+++ b/saleor/graphql/core/fields.py
@@ -25,7 +25,7 @@ class BaseField(graphene.Field):
self.doc_category = kwargs.pop("doc_category", None)
self.webhook_events_info = kwargs.pop("webhook_events_info", None)
- super(BaseField, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
if self.webhook_events_info and auto_webhook_events_info_message:
description = self.description or ""
@@ -50,7 +50,7 @@ class PermissionsField(BaseField):
f"{self.permissions}"
)
- super(PermissionsField, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
if auto_permission_message and self.permissions:
permissions_msg = message_one_of_permissions_required(self.permissions)
description = self.description or ""
@@ -60,7 +60,7 @@ class PermissionsField(BaseField):
resolver = self.resolver or parent_resolver
if self.permissions:
resolver = one_of_permissions_required(self.permissions)(resolver)
- resolver = super(PermissionsField, self).get_resolver(resolver)
+ resolver = super().get_resolver(resolver)
return resolver
@@ -110,7 +110,7 @@ class ConnectionField(PermissionsField):
@property
def type(self):
- type = super(ConnectionField, self).type
+ type = super().type
connection_type = type
if isinstance(type, graphene.NonNull):
connection_type = type.of_type
diff --git a/saleor/graphql/core/filters.py b/saleor/graphql/core/filters.py
index 8192b2d3c5..a493e22e7c 100644
--- a/saleor/graphql/core/filters.py
+++ b/saleor/graphql/core/filters.py
@@ -154,7 +154,7 @@ class GlobalIDFilter(Filter):
_id = None
if value is not None:
_, _id = from_global_id(value)
- return super(GlobalIDFilter, self).filter(qs, _id)
+ return super().filter(qs, _id)
class GlobalIDMultipleChoiceField(MultipleChoiceField):
@@ -177,7 +177,7 @@ class GlobalIDMultipleChoiceFilter(MultipleChoiceFilter):
def filter(self, qs, value):
gids = [from_global_id(v)[1] for v in value]
- return super(GlobalIDMultipleChoiceFilter, self).filter(qs, gids)
+ return super().filter(qs, gids)
class WhereFilterSet(django_filters.FilterSet):
@@ -202,14 +202,9 @@ class WhereFilterSet(django_filters.FilterSet):
if name not in self.form.data:
continue
queryset = self.filters[name].filter(queryset, value)
- assert isinstance(queryset, models.QuerySet), (
- "Expected '%s.%s' to return a QuerySet, but got a %s instead."
- % (
- type(self).__name__,
- name,
- type(queryset).__name__,
- )
- )
+ assert isinstance(
+ queryset, models.QuerySet
+ ), f"Expected '{type(self).__name__}.{name}' to return a QuerySet, but got a {type(queryset).__name__} instead."
return queryset
@@ -246,7 +241,7 @@ class WhereFilter(Filter):
def filter(self, qs, value):
if self.distinct:
qs = qs.distinct()
- lookup = "%s__%s" % (self.field_name, self.lookup_expr)
+ lookup = f"{self.field_name}__{self.lookup_expr}"
qs = self.get_method(qs)(**{lookup: value})
return qs
@@ -306,7 +301,7 @@ class GlobalIDMultipleChoiceWhereFilter(MultipleChoiceFilter, WhereFilter):
def filter(self, qs, value):
gids = [from_global_id(v)[1] for v in value]
- return super(GlobalIDMultipleChoiceWhereFilter, self).filter(qs, gids)
+ return super().filter(qs, gids)
class GlobalIDWhereFilter(WhereFilter):
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 1b24f25513..7b0592f2fd 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -1,16 +1,11 @@
import os.path
import secrets
+from collections.abc import Collection, Iterable
from enum import Enum
from itertools import chain
from typing import (
Any,
- Collection,
- Dict,
- Iterable,
- List,
Optional,
- Tuple,
- Type,
TypeVar,
Union,
cast,
@@ -176,7 +171,7 @@ class BaseMutation(graphene.Mutation):
support_meta_field=False,
support_private_meta_field=False,
auto_webhook_events_message: bool = True,
- webhook_events_info: Optional[List[WebhookEventInfo]] = None,
+ webhook_events_info: Optional[list[WebhookEventInfo]] = None,
**options,
):
if not _meta:
@@ -233,7 +228,7 @@ class BaseMutation(graphene.Mutation):
def _get_node_by_pk(
cls,
info: ResolveInfo,
- graphene_type: Type[ModelObjectType[MT]],
+ graphene_type: type[ModelObjectType[MT]],
pk: Union[int, str],
qs=None,
) -> Optional[MT]:
@@ -283,7 +278,7 @@ class BaseMutation(graphene.Mutation):
node_id: str,
*,
field: str = "id",
- only_type: Type[ModelObjectType[MT]],
+ only_type: type[ModelObjectType[MT]],
qs: Any = None,
code: str = "not_found",
) -> MT:
@@ -297,7 +292,7 @@ class BaseMutation(graphene.Mutation):
node_id: Optional[str],
*,
field: str = "id",
- only_type: Type[ModelObjectType[MT]],
+ only_type: type[ModelObjectType[MT]],
qs: Any = None,
code: str = "not_found",
) -> Optional[MT]:
@@ -352,7 +347,7 @@ class BaseMutation(graphene.Mutation):
node_id: Optional[str],
*,
field: str = "id",
- only_type: Optional[Type[ObjectType]] = None,
+ only_type: Optional[type[ObjectType]] = None,
qs: Optional[QuerySet] = None,
code: str = "not_found",
) -> Optional[Model]:
@@ -408,15 +403,15 @@ class BaseMutation(graphene.Mutation):
@overload
@classmethod
def get_nodes_or_error(
- cls, ids, field, only_type: Type[ModelObjectType[MT]], qs=None, schema=None
- ) -> List[MT]:
+ cls, ids, field, only_type: type[ModelObjectType[MT]], qs=None, schema=None
+ ) -> list[MT]:
...
@overload
@classmethod
def get_nodes_or_error(
cls, ids, field, only_type: Optional[ObjectType] = None, qs=None, schema=None
- ) -> List[Model]:
+ ) -> list[Model]:
...
@classmethod
@@ -565,7 +560,7 @@ class BaseMutation(graphene.Mutation):
return call_event(func_obj, *func_args, **kwargs)
@classmethod
- def update_metadata(cls, instance, meta_data_list: List, is_private: bool = False):
+ def update_metadata(cls, instance, meta_data_list: list, is_private: bool = False):
if is_private:
instance.store_value_in_private_metadata(
{data.key: data.value for data in meta_data_list}
@@ -576,7 +571,7 @@ class BaseMutation(graphene.Mutation):
)
@classmethod
- def validate_metadata_keys(cls, metadata_list: List[dict]):
+ def validate_metadata_keys(cls, metadata_list: list[dict]):
if metadata_contains_empty_key(metadata_list):
raise ValidationError(
{
@@ -1005,10 +1000,10 @@ class BaseBulkMutation(BaseMutation):
@classmethod
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, ids, **data
- ) -> Tuple[int, Optional[ValidationError]]:
+ ) -> tuple[int, Optional[ValidationError]]:
"""Perform a mutation that deletes a list of model instances."""
clean_instance_ids = []
- errors_dict: Dict[str, List[ValidationError]] = {}
+ errors_dict: dict[str, list[ValidationError]] = {}
# Allow to pass empty list for dummy mutation
if not ids:
return 0, None
@@ -1092,10 +1087,10 @@ class BaseBulkWithRestrictedChannelAccessMutation(BaseBulkMutation):
@classmethod
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, ids, **data
- ) -> Tuple[int, Optional[ValidationError]]:
+ ) -> tuple[int, Optional[ValidationError]]:
"""Perform a mutation that deletes a list of model instances."""
clean_instance_ids = []
- errors_dict: Dict[str, List[ValidationError]] = {}
+ errors_dict: dict[str, list[ValidationError]] = {}
# Allow to pass empty list for dummy mutation
if not ids:
return 0, None
diff --git a/saleor/graphql/core/tests/test_scalars.py b/saleor/graphql/core/tests/test_scalars.py
index 7a68b5d5fa..b15a7755da 100644
--- a/saleor/graphql/core/tests/test_scalars.py
+++ b/saleor/graphql/core/tests/test_scalars.py
@@ -1,4 +1,5 @@
-import mock
+from unittest import mock
+
import pytest
from ....order.models import Order
diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.py
index 339da215e8..9c672215bc 100644
--- a/saleor/graphql/core/tests/test_view.py
+++ b/saleor/graphql/core/tests/test_view.py
@@ -140,7 +140,7 @@ def test_query_is_dict(client):
def test_graphql_execution_exception(monkeypatch, api_client):
def mocked_execute(*args, **kwargs):
- raise IOError("Spanish inquisition")
+ raise OSError("Spanish inquisition")
monkeypatch.setattr("graphql.backend.core.execute_and_validate", mocked_execute)
response = api_client.post_graphql("{ shop { name }}")
diff --git a/saleor/graphql/core/types/base.py b/saleor/graphql/core/types/base.py
index 6fa2362b41..496ff56030 100644
--- a/saleor/graphql/core/types/base.py
+++ b/saleor/graphql/core/types/base.py
@@ -18,7 +18,7 @@ class BaseObjectType(ObjectType):
):
cls.doc_category = doc_category
cls.webhook_events_info = webhook_events_info
- super(BaseObjectType, cls).__init_subclass_with_meta__(
+ super().__init_subclass_with_meta__(
interfaces=interfaces,
possible_types=possible_types,
default_resolver=default_resolver,
@@ -33,9 +33,7 @@ class BaseInputObjectType(InputObjectType):
cls, container=None, _meta=None, doc_category=None, **options
):
cls.doc_category = doc_category
- super(BaseInputObjectType, cls).__init_subclass_with_meta__(
- container=container, _meta=_meta, **options
- )
+ super().__init_subclass_with_meta__(container=container, _meta=_meta, **options)
class BaseEnum(Enum):
@@ -44,9 +42,7 @@ class BaseEnum(Enum):
cls, enum=None, _meta=None, doc_category=None, **options
):
cls.doc_category = doc_category
- super(BaseEnum, cls).__init_subclass_with_meta__(
- enum=enum, _meta=_meta, **options
- )
+ super().__init_subclass_with_meta__(enum=enum, _meta=_meta, **options)
class BaseConnection(Connection):
@@ -58,6 +54,4 @@ class BaseConnection(Connection):
cls, node=None, name=None, doc_category=None, **options
):
cls.doc_category = doc_category
- super(BaseConnection, cls).__init_subclass_with_meta__(
- node=node, name=name, **options
- )
+ super().__init_subclass_with_meta__(node=node, name=name, **options)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 71935a070e..26d39f5b64 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -116,7 +116,7 @@ class NonNullList(graphene.List):
def __init__(self, of_type, *args, **kwargs):
of_type = graphene.NonNull(of_type)
- super(NonNullList, self).__init__(of_type, *args, **kwargs)
+ super().__init__(of_type, *args, **kwargs)
class CountryDisplay(graphene.ObjectType):
diff --git a/saleor/graphql/core/types/filter_input.py b/saleor/graphql/core/types/filter_input.py
index 4abaae1475..2bea0dfff7 100644
--- a/saleor/graphql/core/types/filter_input.py
+++ b/saleor/graphql/core/types/filter_input.py
@@ -39,7 +39,7 @@ class GraphQLFilterSetMixin(BaseFilterSet):
def get_filterset_class(filterset_class=None):
return type(
- "GraphQL{}".format(filterset_class.__name__),
+ f"GraphQL{filterset_class.__name__}",
(filterset_class, GraphQLFilterSetMixin),
{},
)
diff --git a/saleor/graphql/core/types/model.py b/saleor/graphql/core/types/model.py
index ca17e36d1a..b16cfb478f 100644
--- a/saleor/graphql/core/types/model.py
+++ b/saleor/graphql/core/types/model.py
@@ -1,5 +1,5 @@
import copy
-from typing import Generic, Optional, Type, TypeVar
+from typing import Generic, Optional, TypeVar
from uuid import UUID
from django.db.models import Model, Q
@@ -55,7 +55,7 @@ class ModelObjectType(Generic[MT], BaseObjectType):
if not options["doc_category"] and doc_category_key in DOC_CATEGORY_MAP:
options["doc_category"] = DOC_CATEGORY_MAP[doc_category_key]
- super(ModelObjectType, cls).__init_subclass_with_meta__(
+ super().__init_subclass_with_meta__(
interfaces=interfaces,
possible_types=possible_types,
default_resolver=default_resolver,
@@ -113,5 +113,5 @@ class ModelObjectType(Generic[MT], BaseObjectType):
return None
@classmethod
- def get_model(cls) -> Type[MT]:
+ def get_model(cls) -> type[MT]:
return cls._meta.model
diff --git a/saleor/graphql/core/types/order_or_checkout.py b/saleor/graphql/core/types/order_or_checkout.py
index a1dfce4483..156e27f8c3 100644
--- a/saleor/graphql/core/types/order_or_checkout.py
+++ b/saleor/graphql/core/types/order_or_checkout.py
@@ -24,7 +24,7 @@ class OrderOrCheckoutBase(graphene.Union):
return checkout_types.Checkout
if isinstance(instance, Order):
return order_types.Order
- return super(OrderOrCheckoutBase, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
class OrderOrCheckout(OrderOrCheckoutBase):
diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.py
index 293e8f2286..87965e5524 100644
--- a/saleor/graphql/core/types/taxes.py
+++ b/saleor/graphql/core/types/taxes.py
@@ -55,7 +55,7 @@ class TaxSourceLine(graphene.Union):
return checkout_types.CheckoutLine
if isinstance(instance, OrderLine):
return order_types.OrderLine
- return super(TaxSourceLine, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
class TaxableObjectLine(BaseObjectType):
diff --git a/saleor/graphql/core/types/user_or_app.py b/saleor/graphql/core/types/user_or_app.py
index 7c9e435bf3..a6ce7aee4a 100644
--- a/saleor/graphql/core/types/user_or_app.py
+++ b/saleor/graphql/core/types/user_or_app.py
@@ -19,4 +19,4 @@ class UserOrApp(graphene.Union):
return account_types.User
if isinstance(instance, app_models.App):
return account_types.App
- return super(UserOrApp, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index ab7f6c5622..f4dd3512d4 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -2,7 +2,7 @@ import binascii
import os
import secrets
from dataclasses import dataclass
-from typing import List, Literal, Optional, Tuple, Type, Union, overload
+from typing import Literal, Optional, Union, overload
import graphene
from django.core.exceptions import ValidationError
@@ -47,22 +47,22 @@ def from_global_id_or_error(
global_id: str,
only_type: Union[ObjectType, str, None] = None,
raise_error: Literal[True] = True,
-) -> Tuple[str, str]:
+) -> tuple[str, str]:
...
@overload
def from_global_id_or_error(
global_id: str,
- only_type: Union[Type[ObjectType], str, None] = None,
+ only_type: Union[type[ObjectType], str, None] = None,
raise_error: bool = False,
-) -> Union[Tuple[str, str], Tuple[str, None]]:
+) -> Union[tuple[str, str], tuple[str, None]]:
...
def from_global_id_or_error(
global_id: str,
- only_type: Union[Type[ObjectType], str, None] = None,
+ only_type: Union[type[ObjectType], str, None] = None,
raise_error: bool = False,
):
"""Resolve global ID or raise GraphQLError.
@@ -154,7 +154,7 @@ CHECKOUT_CALCULATE_TAXES_MESSAGE = (
)
-def message_webhook_events(webhook_events: List[WebhookEventInfo]) -> str:
+def message_webhook_events(webhook_events: list[WebhookEventInfo]) -> str:
description = "\n\nTriggers the following webhook events:"
for event in webhook_events:
webhook_type = "async" if event.type in WebhookEventAsyncType.ALL else "sync"
diff --git a/saleor/graphql/core/utils/reordering.py b/saleor/graphql/core/utils/reordering.py
index 88ee10b4c1..a7d3a0e25a 100644
--- a/saleor/graphql/core/utils/reordering.py
+++ b/saleor/graphql/core/utils/reordering.py
@@ -1,6 +1,5 @@
from collections import OrderedDict
from dataclasses import dataclass
-from typing import Dict, List, Tuple
from django.db import transaction
from django.db.models import F, QuerySet
@@ -21,7 +20,7 @@ class FinalSortOrder:
class Reordering:
- def __init__(self, qs: QuerySet, operations: Dict[int, int], field: str):
+ def __init__(self, qs: QuerySet, operations: dict[int, int], field: str):
self.qs = qs
self.operations = operations
self.field = field
@@ -29,11 +28,11 @@ class Reordering:
# Will contain the original data, before sorting
# This will be useful to look for the sort orders that
# actually were changed
- self.old_sort_map: Dict[int, str] = {}
+ self.old_sort_map: dict[int, str] = {}
# Will contain the list of keys kept
# in correct order in accordance to their sort order
- self.ordered_pks: List[int] = []
+ self.ordered_pks: list[int] = []
@cached_property
def ordered_node_map(self):
@@ -58,7 +57,7 @@ class Reordering:
return ordering_map
- def calculate_new_sort_order(self, pk, move) -> Tuple[int, int, int]:
+ def calculate_new_sort_order(self, pk, move) -> tuple[int, int, int]:
"""Return the proper sort order for the current operation.
Allows to properly move the node in a given direction with by amount.
@@ -151,7 +150,7 @@ class Reordering:
self.commit()
-def perform_reordering(qs: QuerySet, operations: Dict[int, int], field: str = "moves"):
+def perform_reordering(qs: QuerySet, operations: dict[int, int], field: str = "moves"):
"""Perform reordering over given operations on a queryset.
This utility takes a set of operations containing a node
diff --git a/saleor/graphql/core/validators/query_cost.py b/saleor/graphql/core/validators/query_cost.py
index edba221f9e..10607dffec 100644
--- a/saleor/graphql/core/validators/query_cost.py
+++ b/saleor/graphql/core/validators/query_cost.py
@@ -1,6 +1,6 @@
from functools import reduce
from operator import add, mul
-from typing import Any, Dict, List, Optional, Union, cast
+from typing import Any, Optional, Union, cast
from graphql import (
GraphQLError,
@@ -30,15 +30,15 @@ CostAwareNode = Union[
OperationDefinition,
]
-GraphQLFieldMap = Dict[str, GraphQLField]
+GraphQLFieldMap = dict[str, GraphQLField]
class CostValidator(ValidationRule):
maximum_cost: int
default_cost: int = 0
default_complexity: int = 1
- variables: Optional[Dict] = None
- cost_map: Optional[Dict[str, Dict[str, Any]]] = None
+ variables: Optional[dict] = None
+ cost_map: Optional[dict[str, dict[str, Any]]] = None
def __init__(
self,
@@ -46,8 +46,8 @@ class CostValidator(ValidationRule):
*,
default_cost: int = 0,
default_complexity: int = 1,
- variables: Optional[Dict] = None,
- cost_map: Optional[Dict[str, Dict[str, Any]]] = None,
+ variables: Optional[dict] = None,
+ cost_map: Optional[dict[str, dict[str, Any]]] = None,
): # pylint: disable=super-init-not-called
self.maximum_cost = maximum_cost
self.variables = variables
@@ -55,7 +55,7 @@ class CostValidator(ValidationRule):
self.default_cost = default_cost
self.default_complexity = default_complexity
self.cost = 0
- self.operation_multipliers: List[Any] = []
+ self.operation_multipliers: list[Any] = []
def __call__(self, context: ValidationContext):
self.context = context
@@ -79,7 +79,7 @@ class CostValidator(ValidationRule):
continue
field_type = get_named_type(field.type)
try:
- field_args: Dict[str, Any] = get_argument_values(
+ field_args: dict[str, Any] = get_argument_values(
field.args,
child_node.arguments,
self.variables,
@@ -162,9 +162,9 @@ class CostValidator(ValidationRule):
return reduce(mul, self.operation_multipliers, complexity)
return complexity
- def get_args_from_cost_map(self, node: Field, parent_type: str, field_args: Dict):
+ def get_args_from_cost_map(self, node: Field, parent_type: str, field_args: dict):
cost_args = None
- cost_map = cast(Dict[Any, Dict], self.cost_map)
+ cost_map = cast(dict[Any, dict], self.cost_map)
if parent_type in cost_map:
cost_args = cost_map[parent_type].get(node.name.value)
if not cost_args:
@@ -176,7 +176,7 @@ class CostValidator(ValidationRule):
)
return cost_args
- def get_multipliers_from_string(self, multipliers: List[str], field_args):
+ def get_multipliers_from_string(self, multipliers: list[str], field_args):
accessors = [s.split(".") for s in multipliers]
multipliers: Any = []
for accessor in accessors:
@@ -209,8 +209,8 @@ class CostValidator(ValidationRule):
node: Any,
key: Optional[Union[int, str]],
parent: Any,
- path: List[Union[int, str]],
- ancestors: List[Any],
+ path: list[Union[int, str]],
+ ancestors: list[Any],
):
if isinstance(node, OperationDefinition):
self.enter_operation_definition(node, key, parent, path, ancestors)
@@ -220,14 +220,14 @@ class CostValidator(ValidationRule):
node: Any,
key: Optional[Union[int, str]],
parent: Any,
- path: List[Union[int, str]],
- ancestors: List[Any],
+ path: list[Union[int, str]],
+ ancestors: list[Any],
):
if isinstance(node, OperationDefinition):
self.leave_operation_definition(node, key, parent, path, ancestors)
-def validate_cost_map(cost_map: Dict[str, Dict[str, Any]], schema: GraphQLSchema):
+def validate_cost_map(cost_map: dict[str, dict[str, Any]], schema: GraphQLSchema):
type_map = schema.get_type_map()
for type_name, type_fields in cost_map.items():
if type_name not in type_map:
@@ -271,8 +271,8 @@ def cost_validator(
*,
default_cost: int = 0,
default_complexity: int = 1,
- variables: Optional[Dict] = None,
- cost_map: Optional[Dict[str, Dict[str, Any]]] = None,
+ variables: Optional[dict] = None,
+ cost_map: Optional[dict[str, dict[str, Any]]] = None,
) -> CostValidator:
return CostValidator(
maximum_cost=maximum_cost,
diff --git a/saleor/graphql/csv/mutations/base_export.py b/saleor/graphql/csv/mutations/base_export.py
index 5ce4967a36..86675efb75 100644
--- a/saleor/graphql/csv/mutations/base_export.py
+++ b/saleor/graphql/csv/mutations/base_export.py
@@ -1,4 +1,5 @@
-from typing import Dict, List, Mapping, Union
+from collections.abc import Mapping
+from typing import Union
import graphene
from django.core.exceptions import ValidationError
@@ -30,7 +31,7 @@ class BaseExportMutation(BaseMutation):
return {"all": ""}
@classmethod
- def clean_ids(cls, input, only_type) -> Dict[str, List[str]]:
+ def clean_ids(cls, input, only_type) -> dict[str, list[str]]:
ids = input.get("ids", [])
if not ids:
raise ValidationError(
@@ -45,7 +46,7 @@ class BaseExportMutation(BaseMutation):
return {"ids": pks}
@staticmethod
- def clean_filter(input) -> Dict[str, dict]:
+ def clean_filter(input) -> dict[str, dict]:
filter = input.get("filter")
if not filter:
raise ValidationError(
diff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.py
index 5bb4c84939..9e906a6857 100644
--- a/saleor/graphql/decorators.py
+++ b/saleor/graphql/decorators.py
@@ -1,6 +1,7 @@
+from collections.abc import Iterable
from enum import Enum
from functools import wraps
-from typing import Iterable, List, Union
+from typing import Union
from graphene import ResolveInfo
@@ -65,7 +66,7 @@ def account_passes_test_for_attribute(test_func):
return decorator
-def permission_required(perm: Union[BasePermissionEnum, List[BasePermissionEnum]]):
+def permission_required(perm: Union[BasePermissionEnum, list[BasePermissionEnum]]):
def check_perms(context):
if isinstance(perm, Enum):
perms = [perm]
@@ -121,7 +122,7 @@ def check_attribute_required_permissions():
def check_perms(context, attribute):
requestor = get_user_or_app_from_context(context)
- permissions: List[BasePermissionEnum]
+ permissions: list[BasePermissionEnum]
if attribute.type == AttributeType.PAGE_TYPE:
permissions = [
PagePermissions.MANAGE_PAGES,
diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.py
index e3db683860..87c6992ef1 100644
--- a/saleor/graphql/discount/dataloaders.py
+++ b/saleor/graphql/discount/dataloaders.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import List, Optional
+from typing import Optional
from django.db.models import Exists, F, OuterRef
from promise import Promise
@@ -129,7 +129,7 @@ class VoucherInfoByVoucherCodeLoader(DataLoader[str, Optional[VoucherInfo]]):
category_pks_map[voucher_id].append(category_id)
for voucher_id, collection_id in voucher_collections:
collection_pks_map[voucher_id].append(collection_id)
- voucher_infos: List[Optional[VoucherInfo]] = []
+ voucher_infos: list[Optional[VoucherInfo]] = []
for code in keys:
voucher = vouchers_map.get(code)
if not voucher:
diff --git a/saleor/graphql/discount/filters.py b/saleor/graphql/discount/filters.py
index 128a44a7cd..17d2b5555e 100644
--- a/saleor/graphql/discount/filters.py
+++ b/saleor/graphql/discount/filters.py
@@ -1,5 +1,4 @@
import decimal
-from typing import List
import django_filters
from django.db.models import Exists, OuterRef, Q
@@ -37,7 +36,7 @@ from .enums import DiscountStatusEnum, DiscountValueTypeEnum, VoucherDiscountTyp
def filter_status(
- qs: VoucherQueryset, _, value: List[DiscountStatusEnum]
+ qs: VoucherQueryset, _, value: list[DiscountStatusEnum]
) -> VoucherQueryset:
if not value:
return qs
@@ -57,7 +56,7 @@ def filter_times_used(qs, _, value):
def filter_discount_type(
- qs: VoucherQueryset, _, values: List[VoucherDiscountType]
+ qs: VoucherQueryset, _, values: list[VoucherDiscountType]
) -> VoucherQueryset:
if values:
query = Q()
diff --git a/saleor/graphql/discount/mutations/bulk_mutations.py b/saleor/graphql/discount/mutations/bulk_mutations.py
index 54b2530f10..c7463f586a 100644
--- a/saleor/graphql/discount/mutations/bulk_mutations.py
+++ b/saleor/graphql/discount/mutations/bulk_mutations.py
@@ -1,4 +1,4 @@
-from typing import Optional, Tuple
+from typing import Optional
import graphene
from django.core.exceptions import ValidationError
@@ -53,7 +53,7 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
@classmethod
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, ids, **data
- ) -> Tuple[int, Optional[ValidationError]]:
+ ) -> tuple[int, Optional[ValidationError]]:
"""Perform a mutation that deletes a list of model instances."""
try:
instances = cls.get_promotion_instances(ids)
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_create.py b/saleor/graphql/discount/mutations/promotion/promotion_create.py
index ad9fd46c3d..60b25d02b2 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_create.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_create.py
@@ -1,6 +1,5 @@
from collections import defaultdict
from datetime import datetime
-from typing import DefaultDict, List, Tuple
import graphene
import pytz
@@ -97,7 +96,7 @@ class PromotionCreate(ModelMutation):
):
cleaned_input = super().clean_input(info, instance, data, **kwargs)
- errors: DefaultDict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
start_date = cleaned_input.get("start_date") or instance.start_date
end_date = cleaned_input.get("end_date")
try:
@@ -120,8 +119,8 @@ class PromotionCreate(ModelMutation):
cls,
info: ResolveInfo,
rules_data: dict,
- errors: DefaultDict[str, List[ValidationError]],
- ) -> Tuple[list, DefaultDict[str, List[ValidationError]]]:
+ errors: defaultdict[str, list[ValidationError]],
+ ) -> tuple[list, defaultdict[str, list[ValidationError]]]:
cleaned_rules = []
for index, rule_data in enumerate(rules_data):
if channel_ids := rule_data.get("channels"):
@@ -136,10 +135,10 @@ class PromotionCreate(ModelMutation):
def clean_channels(
cls,
info: ResolveInfo,
- channel_ids: List[str],
+ channel_ids: list[str],
index: int,
- errors: DefaultDict[str, List[ValidationError]],
- ) -> List[channel_models.Channel]:
+ errors: defaultdict[str, list[ValidationError]],
+ ) -> list[channel_models.Channel]:
try:
channels = get_nodes(channel_ids, Channel, schema=info.schema)
except GraphQLError as e:
@@ -192,7 +191,7 @@ class PromotionCreate(ModelMutation):
cls,
info,
instance: models.Promotion,
- rules: List[models.PromotionRule],
+ rules: list[models.PromotionRule],
):
manager = get_plugin_manager_promise(info.context).get()
has_started = cls.has_started(instance)
@@ -222,7 +221,7 @@ class PromotionCreate(ModelMutation):
cls,
info: ResolveInfo,
instance: models.Promotion,
- rules: List[models.PromotionRule],
+ rules: list[models.PromotionRule],
has_started: bool,
):
app = get_app_promise(info.context).get()
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
index 1e39eb9109..cde00d3212 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import DefaultDict, List
import graphene
from django.core.exceptions import ValidationError
@@ -59,7 +58,7 @@ class PromotionRuleCreate(ModelMutation):
cls, info: ResolveInfo, instance: models.PromotionRule, data: dict, **kwargs
):
cleaned_input = super().clean_input(info, instance, data, **kwargs)
- errors: DefaultDict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
clean_promotion_rule(cleaned_input, errors, PromotionRuleCreateErrorCode)
diff --git a/saleor/graphql/discount/mutations/sale/sale_add_catalogues.py b/saleor/graphql/discount/mutations/sale/sale_add_catalogues.py
index 62bfa1dc83..1e7b150ab4 100644
--- a/saleor/graphql/discount/mutations/sale/sale_add_catalogues.py
+++ b/saleor/graphql/discount/mutations/sale/sale_add_catalogues.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
from .....core.tracing import traced_atomic_transaction
from .....discount.error_codes import DiscountErrorCode
@@ -88,7 +88,7 @@ class SaleAddCatalogues(SaleBaseCatalogueMutation):
@classmethod
def add_items_to_catalogue(
- cls, rules: List[PromotionRule], previous_catalogue_info: CatalogueInfo, input
+ cls, rules: list[PromotionRule], previous_catalogue_info: CatalogueInfo, input
) -> Optional[dict]:
catalogue_info_to_add = cls.get_catalogue_info_from_input(input)
if any(catalogue_info_to_add):
diff --git a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
index 5ceea3ecfa..42742a2862 100644
--- a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
+++ b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import DefaultDict, Set, Union
+from typing import Union
import graphene
from django.core.exceptions import ValidationError
@@ -18,7 +18,7 @@ from ...utils import (
)
from ..voucher.voucher_add_catalogues import CatalogueInput
-CatalogueInfo = DefaultDict[str, Set[Union[int, str]]]
+CatalogueInfo = defaultdict[str, set[Union[int, str]]]
class SaleBaseCatalogueMutation(BaseMutation):
diff --git a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
index 35340815e9..f255e281f5 100644
--- a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import Dict, List, Tuple, cast
+from typing import cast
import graphene
from django.core.exceptions import ValidationError
@@ -80,11 +80,11 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):
cls,
promotion: Promotion,
exemplary_rule: PromotionRule,
- add_channels: List[Dict],
+ add_channels: list[dict],
):
channel_id_rule_map = cls.get_channe_id_to_rule_map(promotion)
- rules_to_create: List[Tuple[Channel, PromotionRule]] = []
- rules_to_update: List[Tuple[Channel, PromotionRule]] = []
+ rules_to_create: list[tuple[Channel, PromotionRule]] = []
+ rules_to_update: list[tuple[Channel, PromotionRule]] = []
for add_channel in add_channels:
channel = add_channel["channel"]
discount_value = add_channel["discount_value"]
@@ -147,7 +147,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):
}
@classmethod
- def remove_channels(cls, promotion: Promotion, remove_channels: List[int]):
+ def remove_channels(cls, promotion: Promotion, remove_channels: list[int]):
rules = promotion.rules.all()
PromotionRuleChannel = PromotionRule.channels.through
rule_channel = PromotionRuleChannel.objects.filter(
@@ -170,7 +170,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):
cls,
cleaned_channels,
sale_type,
- errors: defaultdict[str, List[ValidationError]],
+ errors: defaultdict[str, list[ValidationError]],
error_code,
):
channels_with_invalid_value_precision = []
@@ -218,7 +218,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):
_info: ResolveInfo,
promotion: Promotion,
rule: PromotionRule,
- cleaned_input: Dict,
+ cleaned_input: dict,
):
with traced_atomic_transaction():
cls.add_channels(promotion, rule, cleaned_input.get("add_channels", []))
@@ -246,7 +246,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):
rule = cast(PromotionRule, rule)
sale_type = rule.reward_value_type
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
cleaned_channels = cls.clean_channels(
info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
)
diff --git a/saleor/graphql/discount/mutations/sale/sale_remove_catalogues.py b/saleor/graphql/discount/mutations/sale/sale_remove_catalogues.py
index c0a11875da..f7ef6414d7 100644
--- a/saleor/graphql/discount/mutations/sale/sale_remove_catalogues.py
+++ b/saleor/graphql/discount/mutations/sale/sale_remove_catalogues.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
from .....core.tracing import traced_atomic_transaction
from .....discount.error_codes import DiscountErrorCode
@@ -90,7 +90,7 @@ class SaleRemoveCatalogues(SaleBaseCatalogueMutation):
@classmethod
def remove_items_from_catalogue(
- cls, rules: List[PromotionRule], previous_catalogue_info: CatalogueInfo, input
+ cls, rules: list[PromotionRule], previous_catalogue_info: CatalogueInfo, input
) -> Optional[dict]:
if not any(previous_catalogue_info):
return previous_catalogue_info
diff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.py
index 043728b750..b833fb8854 100644
--- a/saleor/graphql/discount/mutations/sale/sale_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_update.py
@@ -1,5 +1,4 @@
from datetime import datetime
-from typing import List
import graphene
import pytz
@@ -129,7 +128,7 @@ class SaleUpdate(ModelMutation):
@classmethod
def update_fields(
- cls, promotion: models.Promotion, rules: List[models.PromotionRule], input
+ cls, promotion: models.Promotion, rules: list[models.PromotionRule], input
):
if name := input.get("name"):
promotion.name = name
diff --git a/saleor/graphql/discount/mutations/utils.py b/saleor/graphql/discount/mutations/utils.py
index 678072478c..f345f1fade 100644
--- a/saleor/graphql/discount/mutations/utils.py
+++ b/saleor/graphql/discount/mutations/utils.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import DefaultDict, Set
import graphene
@@ -16,8 +15,8 @@ CATALOGUE_FIELD_TO_TYPE_NAME = {
def convert_catalogue_info_to_global_ids(
catalogue_info: CatalogueInfo,
-) -> DefaultDict[str, Set[str]]:
- converted_catalogue_info: DefaultDict[str, Set[str]] = defaultdict(set)
+) -> defaultdict[str, set[str]]:
+ converted_catalogue_info: defaultdict[str, set[str]] = defaultdict(set)
for catalogue_field, type_name in CATALOGUE_FIELD_TO_TYPE_NAME.items():
converted_catalogue_info[catalogue_field].update(
diff --git a/saleor/graphql/discount/mutations/voucher/voucher_channel_listing_update.py b/saleor/graphql/discount/mutations/voucher/voucher_channel_listing_update.py
index ea92a82cd9..c4ea17c5d3 100644
--- a/saleor/graphql/discount/mutations/voucher/voucher_channel_listing_update.py
+++ b/saleor/graphql/discount/mutations/voucher/voucher_channel_listing_update.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -116,9 +115,9 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):
@classmethod
def clean_discount_values(
- cls, cleaned_input, voucher, errors: defaultdict[str, List[ValidationError]]
+ cls, cleaned_input, voucher, errors: defaultdict[str, list[ValidationError]]
):
- error_dict: Dict[str, List[ValidationError]] = {
+ error_dict: dict[str, list[ValidationError]] = {
"channels_without_value": [],
"channels_with_invalid_value_precision": [],
"channels_with_invalid_percentage_value": [],
@@ -208,7 +207,7 @@ class VoucherChannelListingUpdate(BaseChannelListingMutation):
cls, _root, info: ResolveInfo, /, *, id, input
):
voucher = cls.get_node_or_error(info, id, only_type=Voucher, field="id")
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
cleaned_input = cls.clean_channels(
info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
)
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py
index 4f9d6bee66..2771e33960 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py
@@ -74,7 +74,7 @@ SALE_BULK_DELETE_MUTATION = """
@mock.patch(
- ("saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event")
+ "saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event"
)
@mock.patch("saleor.plugins.manager.PluginsManager.sale_deleted")
@mock.patch(
@@ -118,7 +118,7 @@ def test_delete_sales(
@mock.patch(
- ("saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event")
+ "saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event"
)
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_delete_sales_triggers_webhook(
@@ -155,7 +155,7 @@ def test_delete_sales_triggers_webhook(
@mock.patch(
- ("saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event")
+ "saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event"
)
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_delete_sales_with_variants_triggers_webhook(
@@ -216,7 +216,7 @@ def test_delete_sales_with_variants_triggers_webhook(
@mock.patch(
- ("saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event")
+ "saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event"
)
@mock.patch("saleor.plugins.manager.PluginsManager.sale_deleted")
@mock.patch(
diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_bulk_delete.py b/saleor/graphql/discount/tests/mutations/test_voucher_bulk_delete.py
index cb5c02a1ad..13b888aa43 100644
--- a/saleor/graphql/discount/tests/mutations/test_voucher_bulk_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_voucher_bulk_delete.py
@@ -71,7 +71,7 @@ def test_delete_vouchers(staff_api_client, voucher_list, permission_manage_disco
@mock.patch(
- ("saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event")
+ "saleor.graphql.discount.mutations." "bulk_mutations.get_webhooks_for_event"
)
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_delete_vouchers_trigger_webhook(
diff --git a/saleor/graphql/discount/types/sales.py b/saleor/graphql/discount/types/sales.py
index b656018817..b9385d2435 100644
--- a/saleor/graphql/discount/types/sales.py
+++ b/saleor/graphql/discount/types/sales.py
@@ -161,7 +161,7 @@ class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):
return (
PredicateByPromotionIdLoader(info.context)
- .load((root.node.id))
+ .load(root.node.id)
.then(_get_categories)
)
diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.py
index 421cf950f2..6b813f5fe8 100644
--- a/saleor/graphql/discount/utils.py
+++ b/saleor/graphql/discount/utils.py
@@ -1,7 +1,7 @@
from collections import defaultdict
from copy import deepcopy
from enum import Enum
-from typing import DefaultDict, Dict, List, Optional, Set, Union, cast
+from typing import Optional, Union, cast
import graphene
from django.db.models import Exists, OuterRef, QuerySet
@@ -24,7 +24,7 @@ from ..product.filters import (
ProductWhere,
)
-PREDICATE_OPERATOR_DATA_T = List[Dict[str, Union[list, dict, str, bool]]]
+PREDICATE_OPERATOR_DATA_T = list[dict[str, Union[list, dict, str, bool]]]
class Operators(Enum):
@@ -33,7 +33,7 @@ class Operators(Enum):
# TODO: move to validators in promotion dir
-def clean_predicate(predicate: Union[Dict[str, Union[dict, list]], list]):
+def clean_predicate(predicate: Union[dict[str, Union[dict, list]], list]):
"""Convert camel cases keys into snake case."""
if isinstance(predicate, list):
return [
@@ -69,7 +69,7 @@ def get_variants_for_promotion(promotion: Promotion) -> ProductVariantQueryset:
def _handle_product_predicate(
- predicate_data: Dict[str, Union[dict, list]]
+ predicate_data: dict[str, Union[dict, list]]
) -> ProductVariantQueryset:
product_qs = where_filter_qs(
Product.objects.all(), {}, ProductWhere, predicate_data, None
@@ -80,7 +80,7 @@ def _handle_product_predicate(
def _handle_variant_predicate(
- predicate_data: Dict[str, Union[dict, list]]
+ predicate_data: dict[str, Union[dict, list]]
) -> ProductVariantQueryset:
return where_filter_qs(
ProductVariant.objects.all(), {}, ProductVariantWhere, predicate_data, None
@@ -88,7 +88,7 @@ def _handle_variant_predicate(
def _handle_collection_predicate(
- predicate_data: Dict[str, Union[dict, list]]
+ predicate_data: dict[str, Union[dict, list]]
) -> ProductVariantQueryset:
collection_qs = where_filter_qs(
Collection.objects.all(), {}, CollectionWhere, predicate_data, None
@@ -105,7 +105,7 @@ def _handle_collection_predicate(
def _handle_category_predicate(
- predicate_data: Dict[str, Union[dict, list]]
+ predicate_data: dict[str, Union[dict, list]]
) -> ProductVariantQueryset:
category_qs = where_filter_qs(
Category.objects.all(), {}, CategoryWhere, predicate_data, None
@@ -135,8 +135,8 @@ def get_variants_for_predicate(
if queryset is None:
queryset = ProductVariant.objects.all()
- and_data: Optional[List[dict]] = predicate.pop("AND", None)
- or_data: Optional[List[dict]] = predicate.pop("OR", None)
+ and_data: Optional[list[dict]] = predicate.pop("AND", None)
+ or_data: Optional[list[dict]] = predicate.pop("OR", None)
if and_data:
queryset = _handle_and_data(queryset, and_data)
@@ -176,18 +176,18 @@ def _handle_or_data(
return queryset
-def contains_filter_operator(input: Dict[str, Union[dict, str, list, bool]]) -> bool:
+def contains_filter_operator(input: dict[str, Union[dict, str, list, bool]]) -> bool:
return any([operator in input for operator in ["AND", "OR", "NOT"]])
def _handle_catalogue_predicate(
queryset: ProductVariantQueryset,
- predicate_data: Dict[str, Union[dict, str, list, bool]],
+ predicate_data: dict[str, Union[dict, str, list, bool]],
operator,
) -> ProductVariantQueryset:
for field, handle_method in PREDICATE_TO_HANDLE_METHOD.items():
if field_data := predicate_data.get(field):
- field_data = cast(Dict[str, Union[dict, list]], field_data)
+ field_data = cast(dict[str, Union[dict, list]], field_data)
if operator == Operators.AND:
queryset &= handle_method(field_data)
else:
@@ -197,7 +197,7 @@ def _handle_catalogue_predicate(
def convert_migrated_sale_predicate_to_model_ids(
catalogue_predicate,
-) -> Optional[Dict[str, List[int]]]:
+) -> Optional[dict[str, list[int]]]:
"""Convert global ids from catalogue predicate of Promotion created from old sale.
All migrated sales have related PromotionRule with "OR" catalogue predicate. This
@@ -225,7 +225,7 @@ def convert_migrated_sale_predicate_to_model_ids(
return None
-CatalogueInfo = DefaultDict[str, Set[Union[int, str]]]
+CatalogueInfo = defaultdict[str, set[Union[int, str]]]
PREDICATE_TO_CATALOGUE_INFO_MAP = {
"collectionPredicate": "collections",
"categoryPredicate": "categories",
@@ -326,7 +326,7 @@ def subtract_catalogues_info(
def create_catalogue_predicate(collection_ids, category_ids, product_ids, variant_ids):
- predicate: Dict[str, List] = {"OR": []}
+ predicate: dict[str, list] = {"OR": []}
if collection_ids:
predicate["OR"].append({"collectionPredicate": {"ids": collection_ids}})
if category_ids:
diff --git a/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py b/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py
index bd50b2ae11..3ad1afa449 100644
--- a/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py
+++ b/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py
@@ -1,4 +1,4 @@
-from typing import Iterable
+from collections.abc import Iterable
import graphene
from django.core.exceptions import ValidationError
diff --git a/saleor/graphql/giftcard/filters.py b/saleor/graphql/giftcard/filters.py
index 67b3baf4de..aad75829f1 100644
--- a/saleor/graphql/giftcard/filters.py
+++ b/saleor/graphql/giftcard/filters.py
@@ -1,4 +1,3 @@
-from typing import List
from uuid import UUID
import django_filters
@@ -134,7 +133,7 @@ class GiftCardFilterInput(FilterInputObjectType):
filterset_class = GiftCardFilter
-def filter_events_by_type(events: List[models.GiftCardEvent], type_value: str):
+def filter_events_by_type(events: list[models.GiftCardEvent], type_value: str):
filtered_events = []
for event in events:
if event.type == type_value:
@@ -142,7 +141,7 @@ def filter_events_by_type(events: List[models.GiftCardEvent], type_value: str):
return filtered_events
-def filter_events_by_orders(events: List[models.GiftCardEvent], order_ids: List[str]):
+def filter_events_by_orders(events: list[models.GiftCardEvent], order_ids: list[str]):
order_pks = _get_order_pks(order_ids)
filtered_events = []
@@ -152,7 +151,7 @@ def filter_events_by_orders(events: List[models.GiftCardEvent], order_ids: List[
return filtered_events
-def _get_order_pks(order_ids: List[str]):
+def _get_order_pks(order_ids: list[str]):
_, order_pks = resolve_global_ids_to_primary_keys(order_ids, "Order")
pks = []
diff --git a/saleor/graphql/giftcard/mutations/gift_card_create.py b/saleor/graphql/giftcard/mutations/gift_card_create.py
index 4a5c78e897..47ae6e09a5 100644
--- a/saleor/graphql/giftcard/mutations/gift_card_create.py
+++ b/saleor/graphql/giftcard/mutations/gift_card_create.py
@@ -1,4 +1,4 @@
-from typing import Iterable
+from collections.abc import Iterable
import graphene
from django.core.exceptions import ValidationError
diff --git a/saleor/graphql/invoice/mutations/invoice_update.py b/saleor/graphql/invoice/mutations/invoice_update.py
index 51723f6f60..c93d9c9115 100644
--- a/saleor/graphql/invoice/mutations/invoice_update.py
+++ b/saleor/graphql/invoice/mutations/invoice_update.py
@@ -1,5 +1,3 @@
-from typing import Dict
-
import graphene
from django.core.exceptions import ValidationError
@@ -60,7 +58,7 @@ class InvoiceUpdate(ModelMutation):
number = instance.number or data.get("number")
url = instance.external_url or data.get("url")
- validation_errors: Dict[str, ValidationError] = {}
+ validation_errors: dict[str, ValidationError] = {}
if not number:
validation_errors["number"] = ValidationError(
"Number need to be set after update operation.",
diff --git a/saleor/graphql/menu/mutations/menu_item_create.py b/saleor/graphql/menu/mutations/menu_item_create.py
index ef2b98e796..5bafba50a6 100644
--- a/saleor/graphql/menu/mutations/menu_item_create.py
+++ b/saleor/graphql/menu/mutations/menu_item_create.py
@@ -1,5 +1,3 @@
-from typing import Type
-
import graphene
from django.core.exceptions import ValidationError
from django.db.models import Model
@@ -102,7 +100,7 @@ class MenuItemCreate(ModelMutation):
def _validate_menu_item_instance(
- cleaned_input: dict, field: str, expected_model: Type[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)
diff --git a/saleor/graphql/menu/mutations/menu_item_move.py b/saleor/graphql/menu/mutations/menu_item_move.py
index b585e67a0b..29d57ea8fd 100644
--- a/saleor/graphql/menu/mutations/menu_item_move.py
+++ b/saleor/graphql/menu/mutations/menu_item_move.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass
-from typing import Dict, List, Optional
+from typing import Optional
import graphene
from django.core.exceptions import ValidationError
@@ -140,10 +140,10 @@ class MenuItemMove(BaseMutation):
cls,
info: ResolveInfo,
menu: models.Menu,
- move_operations: List[MenuItemMoveInput],
- ) -> List[_MenuMoveOperation]:
+ move_operations: list[MenuItemMoveInput],
+ ) -> list[_MenuMoveOperation]:
operations = []
- item_to_current_parent: Dict[int, Optional[models.MenuItem]] = {}
+ item_to_current_parent: dict[int, Optional[models.MenuItem]] = {}
for move in move_operations:
cls.clean_move(move)
operation = cls.get_operation(info, item_to_current_parent, menu, move)
@@ -176,7 +176,7 @@ class MenuItemMove(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
menu: str = data["menu"]
- moves: List[MenuItemMoveInput] = data["moves"]
+ moves: list[MenuItemMoveInput] = data["moves"]
qs = models.Menu.objects.prefetch_related("items")
menu = cls.get_node_or_error(info, menu, only_type=Menu, field="menu", qs=qs)
diff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.py
index 4467b11a73..7cb98d1b2c 100644
--- a/saleor/graphql/meta/mutations/base.py
+++ b/saleor/graphql/meta/mutations/base.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from django.core.exceptions import ValidationError
from graphql.error.base import GraphQLError
@@ -117,7 +115,7 @@ class BaseMetadataMutation(BaseMutation):
)
@classmethod
- def validate_metadata_keys(cls, metadata_list: List[dict]):
+ def validate_metadata_keys(cls, metadata_list: list[dict]):
if metadata_contains_empty_key(metadata_list):
raise ValidationError(
{
diff --git a/saleor/graphql/meta/mutations/delete_metadata.py b/saleor/graphql/meta/mutations/delete_metadata.py
index 431c7ea8e4..c78d4ce38e 100644
--- a/saleor/graphql/meta/mutations/delete_metadata.py
+++ b/saleor/graphql/meta/mutations/delete_metadata.py
@@ -1,4 +1,4 @@
-from typing import List, cast
+from typing import cast
import graphene
@@ -33,7 +33,7 @@ class DeleteMetadata(BaseMetadataMutation):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str, keys: List[str]
+ cls, _root, info: ResolveInfo, /, *, id: str, keys: list[str]
):
instance = cast(models.ModelWithMetadata, cls.get_instance(info, id=id))
if instance:
diff --git a/saleor/graphql/meta/mutations/delete_private_metadata.py b/saleor/graphql/meta/mutations/delete_private_metadata.py
index 178795d6aa..2d7ff39575 100644
--- a/saleor/graphql/meta/mutations/delete_private_metadata.py
+++ b/saleor/graphql/meta/mutations/delete_private_metadata.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from ...core import ResolveInfo
@@ -32,7 +30,7 @@ class DeletePrivateMetadata(BaseMetadataMutation):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str, keys: List[str]
+ cls, _root, info: ResolveInfo, /, *, id: str, keys: list[str]
):
instance = cls.get_instance(info, id=id)
diff --git a/saleor/graphql/meta/mutations/update_metadata.py b/saleor/graphql/meta/mutations/update_metadata.py
index 3f073574e0..c62f5aa1b3 100644
--- a/saleor/graphql/meta/mutations/update_metadata.py
+++ b/saleor/graphql/meta/mutations/update_metadata.py
@@ -1,4 +1,4 @@
-from typing import List, cast
+from typing import cast
import graphene
@@ -34,7 +34,7 @@ class UpdateMetadata(BaseMetadataMutation):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str, input: List
+ cls, _root, info: ResolveInfo, /, *, id: str, input: list
):
instance = cast(models.ModelWithMetadata, cls.get_instance(info, id=id))
if instance:
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index df8c367d92..507b557765 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -1,4 +1,4 @@
-from typing import Any, Callable, Dict, List, Union
+from typing import Any, Callable, Union
from django.core.exceptions import ValidationError
from django.db.models import Exists, OuterRef
@@ -35,13 +35,13 @@ from ..core import ResolveInfo
from ..core.utils import from_global_id_or_error
-def no_permissions(_info: ResolveInfo, _object_pk: Any) -> List[BasePermissionEnum]:
+def no_permissions(_info: ResolveInfo, _object_pk: Any) -> list[BasePermissionEnum]:
return []
def public_user_permissions(
info: ResolveInfo, user_pk: int
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
"""Resolve permission for access to public metadata for user.
Customer have access to own public metadata.
@@ -66,7 +66,7 @@ def public_user_permissions(
def private_user_permissions(
_info: ResolveInfo, user_pk: int
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
user = account_models.User.objects.filter(pk=user_pk).first()
if not user:
raise PermissionDenied()
@@ -77,7 +77,7 @@ def private_user_permissions(
def public_address_permissions(
info: ResolveInfo, address_pk: int
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
"""Resolve permission for access to public metadata for user addresses.
Customer have access to the public metadata of their own addresses.
@@ -120,7 +120,7 @@ def public_address_permissions(
def private_address_permissions(
_info: ResolveInfo, address_pk: int
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
address = (
account_models.Address.objects.filter(pk=address_pk)
.prefetch_related("user_addresses")
@@ -149,31 +149,31 @@ def private_address_permissions(
def product_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [ProductPermissions.MANAGE_PRODUCTS]
def product_type_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES]
-def order_permissions(_info: ResolveInfo, _object_pk: Any) -> List[BasePermissionEnum]:
+def order_permissions(_info: ResolveInfo, _object_pk: Any) -> list[BasePermissionEnum]:
return [OrderPermissions.MANAGE_ORDERS]
def invoice_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [OrderPermissions.MANAGE_ORDERS]
-def menu_permissions(_info: ResolveInfo, _object_pk: Any) -> List[BasePermissionEnum]:
+def menu_permissions(_info: ResolveInfo, _object_pk: Any) -> list[BasePermissionEnum]:
return [MenuPermissions.MANAGE_MENUS]
-def app_permissions(info: ResolveInfo, object_pk: str) -> List[BasePermissionEnum]:
+def app_permissions(info: ResolveInfo, object_pk: str) -> list[BasePermissionEnum]:
auth_token = info.context.decoded_auth_token or {}
app = get_app_promise(info.context).get()
app_id: Union[str, int, None]
@@ -188,7 +188,7 @@ def app_permissions(info: ResolveInfo, object_pk: str) -> List[BasePermissionEnu
def private_app_permssions(
info: ResolveInfo, object_pk: str
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
app = get_app_promise(info.context).get()
if app and app.pk == int(object_pk):
return []
@@ -197,23 +197,23 @@ def private_app_permssions(
def channel_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [ChannelPermissions.MANAGE_CHANNELS]
def checkout_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [CheckoutPermissions.MANAGE_CHECKOUTS]
-def page_permissions(_info: ResolveInfo, _object_pk: Any) -> List[BasePermissionEnum]:
+def page_permissions(_info: ResolveInfo, _object_pk: Any) -> list[BasePermissionEnum]:
return [PagePermissions.MANAGE_PAGES]
def page_type_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES]
@@ -227,19 +227,19 @@ def attribute_permissions(_info: ResolveInfo, attribute_pk: int):
def shipping_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [ShippingPermissions.MANAGE_SHIPPING]
def discount_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [DiscountPermissions.MANAGE_DISCOUNTS]
def public_payment_permissions(
info: ResolveInfo, payment_pk: int
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
context_user = info.context.user
app = get_app_promise(info.context).get()
if app or (context_user and context_user.is_staff):
@@ -251,7 +251,7 @@ def public_payment_permissions(
def private_payment_permissions(
info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
app = get_app_promise(info.context).get()
if app is not None or (info.context.user and info.context.user.is_staff):
return [PaymentPermissions.HANDLE_PAYMENTS]
@@ -260,23 +260,23 @@ def private_payment_permissions(
def gift_card_permissions(
_info: ResolveInfo, _object_pk: Any
-) -> List[BasePermissionEnum]:
+) -> list[BasePermissionEnum]:
return [GiftcardPermissions.MANAGE_GIFT_CARD]
-def tax_permissions(_info: ResolveInfo, _object_pk: int) -> List[BasePermissionEnum]:
+def tax_permissions(_info: ResolveInfo, _object_pk: int) -> list[BasePermissionEnum]:
return [
CheckoutPermissions.HANDLE_TAXES,
CheckoutPermissions.MANAGE_TAXES,
]
-def site_permissions(_info: ResolveInfo, _object_pk: Any) -> List[BasePermissionEnum]:
+def site_permissions(_info: ResolveInfo, _object_pk: Any) -> list[BasePermissionEnum]:
return [SitePermissions.MANAGE_SETTINGS]
-PUBLIC_META_PERMISSION_MAP: Dict[
- str, Callable[[ResolveInfo, Any], List[BasePermissionEnum]]
+PUBLIC_META_PERMISSION_MAP: dict[
+ str, Callable[[ResolveInfo, Any], list[BasePermissionEnum]]
] = {
"Address": public_address_permissions,
"App": app_permissions,
@@ -315,8 +315,8 @@ PUBLIC_META_PERMISSION_MAP: Dict[
}
-PRIVATE_META_PERMISSION_MAP: Dict[
- str, Callable[[ResolveInfo, Any], List[BasePermissionEnum]]
+PRIVATE_META_PERMISSION_MAP: dict[
+ str, Callable[[ResolveInfo, Any], list[BasePermissionEnum]]
] = {
"Address": private_address_permissions,
"App": private_app_permssions,
diff --git a/saleor/graphql/meta/tests/queries/test_order.py b/saleor/graphql/meta/tests/queries/test_order.py
index 63ee985b20..cd93d5fafd 100644
--- a/saleor/graphql/meta/tests/queries/test_order.py
+++ b/saleor/graphql/meta/tests/queries/test_order.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from .....order.models import Order
@@ -757,7 +755,7 @@ query transactionItemMeta($id: ID!){
def execute_query_public_metadata_for_transaction_item(
- client: ApiClient, order: Order, permissions: List[Permission] = None
+ client: ApiClient, order: Order, permissions: list[Permission] = None
):
return execute_query(
QUERY_TRANSACTION_ITEM_PUBLIC_META, client, order, "Order", permissions
@@ -869,7 +867,7 @@ query transactionItemMeta($id: ID!){
def execute_query_private_metadata_for_transaction_item(
- client: ApiClient, order: Order, permissions: List[Permission] = None
+ client: ApiClient, order: Order, permissions: list[Permission] = None
):
return execute_query(
QUERY_TRANSACTION_ITEM_PRIVATE_META, client, order, "Order", permissions
diff --git a/saleor/graphql/meta/tests/queries/test_payment.py b/saleor/graphql/meta/tests/queries/test_payment.py
index bd89e59145..dda2590cc3 100644
--- a/saleor/graphql/meta/tests/queries/test_payment.py
+++ b/saleor/graphql/meta/tests/queries/test_payment.py
@@ -1,5 +1,3 @@
-from typing import List
-
from .....payment.models import Payment
from .....payment.utils import payment_owned_by_user
from .....permission.models import Permission
@@ -24,7 +22,7 @@ QUERY_PAYMENT_PRIVATE_META = """
def execute_query_private_metadata_for_payment(
- client: ApiClient, payment: Payment, permissions: List[Permission] = None
+ client: ApiClient, payment: Payment, permissions: list[Permission] = None
):
return execute_query(
QUERY_PAYMENT_PRIVATE_META, client, payment, "Payment", permissions
@@ -106,7 +104,7 @@ QUERY_PAYMENT_PUBLIC_META = """
def execute_query_public_metadata_for_payment(
- client: ApiClient, payment: Payment, permissions: List[Permission] = None
+ client: ApiClient, payment: Payment, permissions: list[Permission] = None
):
return execute_query(
QUERY_PAYMENT_PUBLIC_META, client, payment, "Payment", permissions
diff --git a/saleor/graphql/meta/tests/queries/utils.py b/saleor/graphql/meta/tests/queries/utils.py
index f9a0fa664a..dadcf1bcda 100644
--- a/saleor/graphql/meta/tests/queries/utils.py
+++ b/saleor/graphql/meta/tests/queries/utils.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from django.http import HttpResponse
@@ -22,7 +20,7 @@ def execute_query(
client: ApiClient,
model: ModelWithMetadata,
model_name: str,
- permissions: List[Permission] = None,
+ permissions: list[Permission] = None,
):
return client.post_graphql(
query_str,
diff --git a/saleor/graphql/meta/tests/test_meta_queries.py b/saleor/graphql/meta/tests/test_meta_queries.py
index 6da3d0ef79..dd4a219ac7 100644
--- a/saleor/graphql/meta/tests/test_meta_queries.py
+++ b/saleor/graphql/meta/tests/test_meta_queries.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from django.http import HttpResponse
@@ -23,7 +21,7 @@ def execute_query(
client: ApiClient,
model: ModelWithMetadata,
model_name: str,
- permissions: List[Permission] = None,
+ permissions: list[Permission] = None,
):
return client.post_graphql(
query_str,
@@ -1063,7 +1061,7 @@ query transactionItemMeta($id: ID!){
def execute_query_public_metadata_for_transaction_item(
- client: ApiClient, order: Order, permissions: List[Permission] = None
+ client: ApiClient, order: Order, permissions: list[Permission] = None
):
return execute_query(
QUERY_TRANSACTION_ITEM_PUBLIC_META, client, order, "Order", permissions
@@ -1173,7 +1171,7 @@ QUERY_PAYMENT_PUBLIC_META = """
def execute_query_public_metadata_for_payment(
- client: ApiClient, payment: Payment, permissions: List[Permission] = None
+ client: ApiClient, payment: Payment, permissions: list[Permission] = None
):
return execute_query(
QUERY_PAYMENT_PUBLIC_META, client, payment, "Payment", permissions
@@ -2771,7 +2769,7 @@ query transactionItemMeta($id: ID!){
def execute_query_private_metadata_for_transaction_item(
- client: ApiClient, order: Order, permissions: List[Permission] = None
+ client: ApiClient, order: Order, permissions: list[Permission] = None
):
return execute_query(
QUERY_TRANSACTION_ITEM_PRIVATE_META, client, order, "Order", permissions
@@ -2886,7 +2884,7 @@ QUERY_PAYMENT_PRIVATE_META = """
def execute_query_private_metadata_for_payment(
- client: ApiClient, payment: Payment, permissions: List[Permission] = None
+ client: ApiClient, payment: Payment, permissions: list[Permission] = None
):
return execute_query(
QUERY_PAYMENT_PRIVATE_META, client, payment, "Payment", permissions
diff --git a/saleor/graphql/order/bulk_mutations/draft_orders.py b/saleor/graphql/order/bulk_mutations/draft_orders.py
index 051b73b1e6..c5a15330fc 100644
--- a/saleor/graphql/order/bulk_mutations/draft_orders.py
+++ b/saleor/graphql/order/bulk_mutations/draft_orders.py
@@ -1,4 +1,5 @@
-from typing import Iterable, Union
+from collections.abc import Iterable
+from typing import Union
from uuid import UUID
import graphene
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py b/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py
index a1ef058f45..50018a0afc 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_cancel.py
@@ -1,4 +1,5 @@
-from typing import Iterable, Union
+from collections.abc import Iterable
+from typing import Union
from uuid import UUID
import graphene
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index d9075b180e..12250c8f94 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -5,7 +5,7 @@ from dataclasses import field as dataclass_field
from dataclasses import fields as dataclass_fields
from datetime import datetime, timedelta
from decimal import Decimal
-from typing import Any, Dict, List, Optional
+from typing import Any, Optional
from uuid import UUID
import graphene
@@ -92,7 +92,7 @@ class OrderBulkFulfillmentLine:
@dataclass
class OrderBulkFulfillment:
fulfillment: Fulfillment
- lines: List[OrderBulkFulfillmentLine]
+ lines: list[OrderBulkFulfillmentLine]
@dataclass
@@ -104,20 +104,20 @@ class OrderBulkOrderLine:
@dataclass
class OrderBulkTransaction:
transaction: TransactionItem
- events: List[TransactionEvent]
+ events: list[TransactionEvent]
@dataclass
class OrderBulkCreateData:
order: Optional[Order] = None
- errors: List[OrderBulkError] = dataclass_field(default_factory=list)
- lines: List[OrderBulkOrderLine] = dataclass_field(default_factory=list)
- notes: List[OrderEvent] = dataclass_field(default_factory=list)
- fulfillments: List[OrderBulkFulfillment] = dataclass_field(default_factory=list)
- transactions: List[OrderBulkTransaction] = dataclass_field(default_factory=list)
- invoices: List[Invoice] = dataclass_field(default_factory=list)
- discounts: List[OrderDiscount] = dataclass_field(default_factory=list)
- gift_cards: List[GiftCard] = dataclass_field(default_factory=list)
+ errors: list[OrderBulkError] = dataclass_field(default_factory=list)
+ lines: list[OrderBulkOrderLine] = dataclass_field(default_factory=list)
+ notes: list[OrderEvent] = dataclass_field(default_factory=list)
+ fulfillments: list[OrderBulkFulfillment] = dataclass_field(default_factory=list)
+ transactions: list[OrderBulkTransaction] = dataclass_field(default_factory=list)
+ invoices: list[Invoice] = dataclass_field(default_factory=list)
+ discounts: list[OrderDiscount] = dataclass_field(default_factory=list)
+ gift_cards: list[GiftCard] = dataclass_field(default_factory=list)
user: Optional[User] = None
billing_address: Optional[Address] = None
channel: Optional[Channel] = None
@@ -157,11 +157,11 @@ class OrderBulkCreateData:
update_order_search_vector(self.order, save=False)
@property
- def all_order_lines(self) -> List[OrderLine]:
+ def all_order_lines(self) -> list[OrderLine]:
return [order_line.line for order_line in self.lines]
@property
- def all_fulfillment_lines(self) -> List[FulfillmentLine]:
+ def all_fulfillment_lines(self) -> list[FulfillmentLine]:
return [
fulfillment_line.line
for fulfillment in self.fulfillments
@@ -169,11 +169,11 @@ class OrderBulkCreateData:
]
@property
- def all_transactions(self) -> List[TransactionItem]:
+ def all_transactions(self) -> list[TransactionItem]:
return [transaction_data.transaction for transaction_data in self.transactions]
@property
- def all_transaction_events(self) -> List[TransactionEvent]:
+ def all_transaction_events(self) -> list[TransactionEvent]:
return [
event
for transaction_data in self.transactions
@@ -181,26 +181,26 @@ class OrderBulkCreateData:
]
@property
- def all_invoices(self) -> List[Invoice]:
+ def all_invoices(self) -> list[Invoice]:
return [invoice for invoice in self.invoices]
@property
- def all_discounts(self) -> List[OrderDiscount]:
+ def all_discounts(self) -> list[OrderDiscount]:
return [discount for discount in self.discounts]
@property
def orderline_fulfillmentlines_map(
self,
- ) -> Dict[UUID, List[OrderBulkFulfillmentLine]]:
- map: Dict[UUID, list] = defaultdict(list)
+ ) -> dict[UUID, list[OrderBulkFulfillmentLine]]:
+ map: dict[UUID, list] = defaultdict(list)
for fulfillment in self.fulfillments:
for fulfillment_line in fulfillment.lines:
map[fulfillment_line.line.order_line.id].append(fulfillment_line)
return map
@property
- def orderline_quantityfulfilled_map(self) -> Dict[UUID, int]:
- map: Dict[UUID, int] = defaultdict(int)
+ def orderline_quantityfulfilled_map(self) -> dict[UUID, int]:
+ map: dict[UUID, int] = defaultdict(int)
for (
order_line,
fulfillment_lines,
@@ -214,7 +214,7 @@ class OrderBulkCreateData:
return map
@property
- def unique_variant_ids(self) -> List[int]:
+ def unique_variant_ids(self) -> list[int]:
return list(
set(
[
@@ -226,21 +226,19 @@ class OrderBulkCreateData:
)
@property
- def unique_warehouse_ids(self) -> List[UUID]:
+ def unique_warehouse_ids(self) -> list[UUID]:
return list(set([order_line.warehouse.id for order_line in self.lines]))
@property
def total_order_quantity(self):
- return sum((order_line.line.quantity for order_line in self.lines))
+ return sum(order_line.line.quantity for order_line in self.lines)
@property
def total_fulfillment_quantity(self):
return sum(
- (
- fulfillment_line.line.quantity
- for fulfillment in self.fulfillments
- for fulfillment_line in fulfillment.lines
- )
+ fulfillment_line.line.quantity
+ for fulfillment in self.fulfillments
+ for fulfillment_line in fulfillment.lines
)
@@ -253,8 +251,8 @@ class DeliveryMethod:
shipping_method_name: Optional[str] = None
shipping_tax_class: Optional[TaxClass] = None
shipping_tax_class_name: Optional[str] = None
- shipping_tax_class_metadata: Optional[List[Dict[str, str]]] = None
- shipping_tax_class_private_metadata: Optional[List[Dict[str, str]]] = None
+ shipping_tax_class_metadata: Optional[list[dict[str, str]]] = None
+ shipping_tax_class_private_metadata: Optional[list[dict[str, str]]] = None
@dataclass
@@ -286,7 +284,7 @@ class LineAmounts:
@dataclass
class ModelIdentifier:
model: str
- keys: List[str] = dataclass_field(default_factory=list)
+ keys: list[str] = dataclass_field(default_factory=list)
@dataclass
@@ -599,7 +597,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
support_private_meta_field = True
@classmethod
- def get_all_instances(cls, orders_input) -> Dict[str, Any]:
+ def get_all_instances(cls, orders_input) -> dict[str, Any]:
"""Retrieve all required instances to process orders.
Return:
@@ -703,7 +701,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
)
# Create dictionary
- object_storage: Dict[str, Any] = {}
+ object_storage: dict[str, Any] = {}
for user in users:
object_storage[f"User.id.{user.id}"] = user
object_storage[f"User.email.{user.email}"] = user
@@ -750,7 +748,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
return date < timezone.now() + timedelta(minutes=MINUTES_DIFF)
@classmethod
- def is_shipping_required(cls, order_input: Dict[str, Any]) -> bool:
+ def is_shipping_required(cls, order_input: dict[str, Any]) -> bool:
for order_line in order_input["lines"]:
if order_line["is_shipping_required"]:
return True
@@ -761,7 +759,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
cls,
order_input,
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
):
date = order_input.get("created_at")
if date and not cls.is_datetime_valid(date):
@@ -855,8 +853,8 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def process_metadata(
cls,
- metadata: List[Dict[str, str]],
- errors: List[OrderBulkError],
+ metadata: list[dict[str, str]],
+ errors: list[OrderBulkError],
path: str,
field: Any,
):
@@ -875,11 +873,11 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def get_instance_with_errors(
cls,
- input: Dict[str, Any],
+ input: dict[str, Any],
model,
- key_map: Dict[str, str],
- errors: List[OrderBulkError],
- object_storage: Dict[str, Any],
+ key_map: dict[str, str],
+ errors: list[OrderBulkError],
+ object_storage: dict[str, Any],
path: str = "",
):
"""Resolve instance based on input data, model and `key_map` argument provided.
@@ -916,9 +914,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def get_instances_related_to_order(
cls,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
):
"""Get all instances of objects needed to create an order."""
user = cls.get_instance_with_errors(
@@ -1028,7 +1026,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def make_order_line_calculations(
cls,
- line_input: Dict[str, Any],
+ line_input: dict[str, Any],
order_data: OrderBulkCreateData,
currency: str,
index: int,
@@ -1122,8 +1120,8 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
cls,
delivery_method: DeliveryMethod,
order_data: OrderBulkCreateData,
- delivery_input: Dict[str, Any],
- object_storage: Dict[str, Any],
+ delivery_input: dict[str, Any],
+ object_storage: dict[str, Any],
) -> OrderAmounts:
"""Calculate all order amount fields."""
@@ -1171,16 +1169,16 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
# Calculate lines
order_lines = order_data.all_order_lines
order_total_gross_amount = Decimal(
- sum((line.total_price_gross_amount for line in order_lines))
+ sum(line.total_price_gross_amount for line in order_lines)
)
order_undiscounted_total_gross_amount = Decimal(
- sum((line.undiscounted_total_price_gross_amount for line in order_lines))
+ sum(line.undiscounted_total_price_gross_amount for line in order_lines)
)
order_total_net_amount = Decimal(
- sum((line.total_price_net_amount for line in order_lines))
+ sum(line.total_price_net_amount for line in order_lines)
)
order_undiscounted_total_net_amount = Decimal(
- sum((line.undiscounted_total_price_net_amount for line in order_lines))
+ sum(line.undiscounted_total_price_net_amount for line in order_lines)
)
return OrderAmounts(
@@ -1196,9 +1194,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def get_delivery_method(
cls,
- delivery_input: Dict[str, Any],
+ delivery_input: dict[str, Any],
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
is_shipping_required: bool,
) -> DeliveryMethod:
delivery_method = DeliveryMethod(is_shipping_required=is_shipping_required)
@@ -1282,7 +1280,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
cls,
note_input,
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
index: int,
) -> Optional[OrderEvent]:
if len(note_input["message"]) > MAX_NOTE_LENGTH:
@@ -1356,7 +1354,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_single_discount(
cls,
- discount_input: Dict[str, Any],
+ discount_input: dict[str, Any],
order_data: OrderBulkCreateData,
order_amounts: OrderAmounts,
currency: str,
@@ -1384,7 +1382,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_single_invoice(
cls,
- invoice_input: Dict[str, Any],
+ invoice_input: dict[str, Any],
order_data: OrderBulkCreateData,
index: int,
) -> Invoice:
@@ -1440,7 +1438,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_single_transaction(
cls,
- transaction_input: Dict[str, Any],
+ transaction_input: dict[str, Any],
order_data: OrderBulkCreateData,
index: int,
):
@@ -1458,7 +1456,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
transaction_data, None, None, save=False
)
money_data = TransactionCreate.get_money_data_from_input(transaction_data)
- events: List[TransactionEvent] = []
+ events: list[TransactionEvent] = []
if money_data:
amountfield_eventtype_map = {
"authorized_value": TransactionEventType.AUTHORIZATION_SUCCESS,
@@ -1499,10 +1497,10 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_single_order_line(
cls,
- order_line_input: Dict[str, Any],
+ order_line_input: dict[str, Any],
order_data: OrderBulkCreateData,
object_storage,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
index: int,
) -> Optional[OrderBulkOrderLine]:
variant = cls.get_instance_with_errors(
@@ -1630,10 +1628,10 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_single_fulfillment(
cls,
- fulfillment_input: Dict[str, Any],
- order_lines: List[OrderBulkOrderLine],
+ fulfillment_input: dict[str, Any],
+ order_lines: list[OrderBulkOrderLine],
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
index: int,
) -> Optional[OrderBulkFulfillment]:
fulfillment = Fulfillment(
@@ -1644,7 +1642,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
)
lines_input = fulfillment_input.get("lines") or []
- lines: List[OrderBulkFulfillmentLine] = []
+ lines: list[OrderBulkFulfillmentLine] = []
line_index = 0
for line_input in lines_input:
path = f"fulfillments.{index}.lines.{line_index}"
@@ -1744,9 +1742,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_notes(
cls,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
):
if notes_input := order_input.get("notes"):
note_index = 0
@@ -1760,7 +1758,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_invoices(
cls,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
order_data: OrderBulkCreateData,
):
if invoices_input := order_input.get("invoices"):
@@ -1774,7 +1772,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_transactions(
cls,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
order_data: OrderBulkCreateData,
):
transactions_input = order_input.get("transactions")
@@ -1787,7 +1785,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_discounts(
cls,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
order_data: OrderBulkCreateData,
order_amounts: OrderAmounts,
):
@@ -1808,9 +1806,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_order_lines(
cls,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
):
order_lines_input = order_input["lines"]
order_line_index = 0
@@ -1830,9 +1828,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_fulfillments(
cls,
- order_input: Dict[str, Any],
+ order_input: dict[str, Any],
order_data: OrderBulkCreateData,
- object_storage: Dict[str, Any],
+ object_storage: dict[str, Any],
):
if fulfillments_input := order_input.get("fulfillments"):
fulfillment_index = 0
@@ -1851,7 +1849,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def create_single_order(
- cls, order_input, object_storage: Dict[str, Any]
+ cls, order_input, object_storage: dict[str, Any]
) -> OrderBulkCreateData:
order_data = OrderBulkCreateData()
cls.validate_order_input(order_input, order_data, object_storage)
@@ -1981,9 +1979,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def handle_stocks(
- cls, orders_data: List[OrderBulkCreateData], stock_update_policy: str
- ) -> List[Stock]:
- variant_ids: List[int] = sum(
+ cls, orders_data: list[OrderBulkCreateData], stock_update_policy: str
+ ) -> list[Stock]:
+ variant_ids: list[int] = sum(
[
order_data.unique_variant_ids
for order_data in orders_data
@@ -1991,7 +1989,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
],
[],
)
- warehouse_ids: List[UUID] = sum(
+ warehouse_ids: list[UUID] = sum(
[
order_data.unique_warehouse_ids
for order_data in orders_data
@@ -2002,7 +2000,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
stocks = Stock.objects.filter(
warehouse__id__in=warehouse_ids, product_variant__id__in=variant_ids
).all()
- stocks_map: Dict[str, Stock] = {
+ stocks_map: dict[str, Stock] = {
f"{stock.product_variant_id}_{stock.warehouse_id}": stock
for stock in stocks
}
@@ -2068,7 +2066,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
stock.quantity_allocated += quantity_to_allocate
- fulfillment_lines: List[OrderBulkFulfillmentLine] = (
+ fulfillment_lines: list[OrderBulkFulfillmentLine] = (
order_data.orderline_fulfillmentlines_map.get(order_line.id) or []
)
for fulfillment_line in fulfillment_lines:
@@ -2082,7 +2080,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
@classmethod
def handle_error_policy(
- cls, orders_data: List[OrderBulkCreateData], error_policy: str
+ cls, orders_data: list[OrderBulkCreateData], error_policy: str
):
errors = [error for order in orders_data for error in order.errors]
if errors:
@@ -2095,7 +2093,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
return orders_data
@classmethod
- def save_data(cls, orders_data: List[OrderBulkCreateData], stocks: List[Stock]):
+ def save_data(cls, orders_data: list[OrderBulkCreateData], stocks: list[Stock]):
for order_data in orders_data:
order_data.set_quantity_fulfilled()
order_data.set_fulfillment_order()
@@ -2114,7 +2112,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
orders = [order_data.order for order_data in orders_data if order_data.order]
Order.objects.bulk_create(orders)
- order_lines: List[OrderLine] = sum(
+ order_lines: list[OrderLine] = sum(
[
order_data.all_order_lines
for order_data in orders_data
@@ -2141,7 +2139,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
Fulfillment.objects.bulk_create(fulfillments)
for order_data in orders_data:
order_data.set_fulfillment_id()
- fulfillment_lines: List[FulfillmentLine] = sum(
+ fulfillment_lines: list[FulfillmentLine] = sum(
[
order_data.all_fulfillment_lines
for order_data in orders_data
@@ -2153,7 +2151,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
Stock.objects.bulk_update(stocks, ["quantity"])
- transactions: List[TransactionItem] = sum(
+ transactions: list[TransactionItem] = sum(
[
order_data.all_transactions
for order_data in orders_data
@@ -2164,7 +2162,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
TransactionItem.objects.bulk_create(transactions)
for order_data in orders_data:
order_data.set_transaction_id()
- transaction_events: List[TransactionEvent] = sum(
+ transaction_events: list[TransactionEvent] = sum(
[
order_data.all_transaction_events
for order_data in orders_data
@@ -2174,13 +2172,13 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
)
TransactionEvent.objects.bulk_create(transaction_events)
- invoices: List[Invoice] = sum(
+ invoices: list[Invoice] = sum(
[order_data.all_invoices for order_data in orders_data if order_data.order],
[],
)
Invoice.objects.bulk_create(invoices)
- discounts: List[OrderDiscount] = sum(
+ discounts: list[OrderDiscount] = sum(
[
order_data.all_discounts
for order_data in orders_data
@@ -2219,12 +2217,12 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
result = OrderBulkCreateResult(order=None, error=error)
return OrderBulkCreate(count=0, results=result)
- orders_data: List[OrderBulkCreateData] = []
+ orders_data: list[OrderBulkCreateData] = []
with traced_atomic_transaction():
# Create dictionary, which stores already resolved objects:
# - key for instances: "{model_name}.{key_name}.{key_value}"
# - key for shipping prices: "shipping_price.{shipping_method_id}"
- object_storage: Dict[str, Any] = cls.get_all_instances(orders_input)
+ object_storage: dict[str, Any] = cls.get_all_instances(orders_input)
for order_input in orders_input:
orders_data.append(cls.create_single_order(order_input, object_storage))
@@ -2232,7 +2230,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
stock_update_policy = (
data.get("stock_update_policy") or StockUpdatePolicy.UPDATE
)
- stocks: List[Stock] = []
+ stocks: list[Stock] = []
cls.handle_error_policy(orders_data, error_policy)
if stock_update_policy != StockUpdatePolicy.SKIP:
diff --git a/saleor/graphql/order/bulk_mutations/utils.py b/saleor/graphql/order/bulk_mutations/utils.py
index 7375fd69c2..155b2cb699 100644
--- a/saleor/graphql/order/bulk_mutations/utils.py
+++ b/saleor/graphql/order/bulk_mutations/utils.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, Type
+from typing import Any
from django.core.exceptions import ValidationError
from graphql.error import GraphQLError
@@ -8,11 +8,11 @@ from ...core.utils import from_global_id_or_error
def get_instance(
- input: Dict[str, Any],
+ input: dict[str, Any],
model,
- key_map: Dict[str, str],
- instance_storage: Dict[str, Any],
- error_enum: Type[OrderBulkCreateErrorCode],
+ key_map: dict[str, str],
+ instance_storage: dict[str, Any],
+ error_enum: type[OrderBulkCreateErrorCode],
path: str = "",
):
"""Resolve instance based on input data, model and `key_map` argument provided.
@@ -40,8 +40,8 @@ def get_instance(
"""
model_name = model.__name__
if len(key_map) > 1:
- if sum((input.get(key) is not None for key in key_map.keys())) > 1:
- args = ", ".join((k for k in key_map.keys()))
+ if sum(input.get(key) is not None for key in key_map.keys()) > 1:
+ args = ", ".join(k for k in key_map.keys())
raise ValidationError(
message=f"Only one of [{args}] arguments can be provided "
f"to resolve {model_name} instance.",
@@ -49,8 +49,8 @@ def get_instance(
params={"path": path},
)
- if all((input.get(key) is None for key in key_map.keys())):
- args = ", ".join((k for k in key_map.keys()))
+ if all(input.get(key) is None for key in key_map.keys()):
+ args = ", ".join(k for k in key_map.keys())
raise ValidationError(
message=f"One of [{args}] arguments must be provided "
f"to resolve {model_name} instance.",
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index cb7ce87660..3a6f244a39 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -1,5 +1,6 @@
from collections import defaultdict
-from typing import DefaultDict, Iterable, List, Tuple, cast
+from collections.abc import Iterable
+from typing import cast
from django.db.models import F
@@ -18,11 +19,11 @@ from ..core.dataloaders import DataLoader
class OrderLinesByVariantIdAndChannelIdLoader(
- DataLoader[Tuple[int, int], List[OrderLine]]
+ DataLoader[tuple[int, int], list[OrderLine]]
):
context_key = "orderline_by_variant_and_channel"
- def batch_load(self, keys: Iterable[Tuple[int, int]]):
+ def batch_load(self, keys: Iterable[tuple[int, int]]):
channel_ids = [key[1] for key in keys]
variant_ids = [key[0] for key in keys]
order_lines = (
@@ -32,8 +33,8 @@ class OrderLinesByVariantIdAndChannelIdLoader(
.order_by("created_at", "id")
)
- order_line_by_variant_and_channel_map: DefaultDict[
- Tuple[int, int], List[OrderLine]
+ order_line_by_variant_and_channel_map: defaultdict[
+ tuple[int, int], list[OrderLine]
] = defaultdict(list)
for order_line in order_lines:
key = (
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 7dda9dfc8b..7ac7c4c5a1 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -255,8 +254,8 @@ class DraftOrderCreate(
def clean_lines(cls, cleaned_input, lines, channel):
if not lines:
return
- grouped_lines_data: List[OrderLineData] = []
- lines_data_map: Dict[str, OrderLineData] = defaultdict(OrderLineData)
+ grouped_lines_data: list[OrderLineData] = []
+ lines_data_map: dict[str, OrderLineData] = defaultdict(OrderLineData)
variant_pks = cls.get_global_ids_or_error(
[line.get("variant_id") for line in lines], ProductVariant, "variant_id"
diff --git a/saleor/graphql/order/mutations/fulfillment_refund_products.py b/saleor/graphql/order/mutations/fulfillment_refund_products.py
index f7d4f78395..91d2715218 100644
--- a/saleor/graphql/order/mutations/fulfillment_refund_products.py
+++ b/saleor/graphql/order/mutations/fulfillment_refund_products.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict
+from typing import Any
import graphene
@@ -96,7 +96,7 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
@classmethod
def clean_input(cls, info: ResolveInfo, order_id, input):
- cleaned_input: Dict[str, Any] = {}
+ cleaned_input: dict[str, Any] = {}
amount_to_refund = input.get("amount_to_refund")
include_shipping_costs = input["include_shipping_costs"]
diff --git a/saleor/graphql/order/mutations/fulfillment_return_products.py b/saleor/graphql/order/mutations/fulfillment_return_products.py
index e7bf364acf..f700b4e97b 100644
--- a/saleor/graphql/order/mutations/fulfillment_return_products.py
+++ b/saleor/graphql/order/mutations/fulfillment_return_products.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict
+from typing import Any
import graphene
@@ -117,7 +117,7 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
@classmethod
def clean_input(cls, info: ResolveInfo, order_id, input):
- cleaned_input: Dict[str, Any] = {}
+ cleaned_input: dict[str, Any] = {}
amount_to_refund = input.get("amount_to_refund")
include_shipping_costs = input["include_shipping_costs"]
refund = input["refund"]
diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.py
index a365e8a424..970e915d07 100644
--- a/saleor/graphql/order/mutations/order_fulfill.py
+++ b/saleor/graphql/order/mutations/order_fulfill.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import DefaultDict, List, Optional
+from typing import Optional
from uuid import UUID
import graphene
@@ -198,8 +198,8 @@ class OrderFulfill(BaseMutation):
)
@classmethod
- def check_total_quantity_of_items(cls, quantities_for_lines: List[List[int]]):
- flat_quantities: List[int] = sum(quantities_for_lines, [])
+ def check_total_quantity_of_items(cls, quantities_for_lines: list[list[int]]):
+ flat_quantities: list[int] = sum(quantities_for_lines, [])
if sum(flat_quantities) <= 0:
raise ValidationError(
{
@@ -232,7 +232,7 @@ class OrderFulfill(BaseMutation):
]
cls.check_warehouses_for_duplicates(warehouse_ids_for_lines)
- quantities_for_lines: List[List[int]] = [
+ quantities_for_lines: list[list[int]] = [
[stock["quantity"] for stock in line["stocks"]] for line in lines
]
@@ -249,8 +249,8 @@ class OrderFulfill(BaseMutation):
cls.check_total_quantity_of_items(quantities_for_lines)
- lines_for_warehouses: DefaultDict[
- UUID, List[OrderFulfillmentLineInfo]
+ lines_for_warehouses: defaultdict[
+ UUID, list[OrderFulfillmentLineInfo]
] = defaultdict(list)
for line, order_line in zip(lines, order_lines):
for stock in line["stocks"]:
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index ce0546a88a..c9d02737bd 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -1,5 +1,4 @@
from collections import defaultdict, namedtuple
-from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -65,8 +64,8 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
def validate_lines(
cls, info: ResolveInfo, data, existing_lines_info, variants_data
):
- grouped_lines_data: List[OrderLineData] = []
- lines_data_map: Dict[str, OrderLineData] = defaultdict(OrderLineData)
+ grouped_lines_data: list[OrderLineData] = []
+ lines_data_map: dict[str, OrderLineData] = defaultdict(OrderLineData)
variants_from_existing_lines = [
line_info.line.variant_id for line_info in existing_lines_info
@@ -136,7 +135,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
@staticmethod
def add_lines_to_order(order, lines_data, user, app, manager):
- added_lines: List[OrderLine] = []
+ added_lines: list[OrderLine] = []
try:
for line_data in lines_data:
line = add_variant_to_order(
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index 0d5c136fc3..7db3cfe5d5 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
import graphene
from django.core.exceptions import ValidationError
@@ -72,7 +72,7 @@ def search_string_in_kwargs(kwargs: dict) -> bool:
return bool(filter_search.strip())
-def sort_field_from_kwargs(kwargs: dict) -> Optional[List[str]]:
+def sort_field_from_kwargs(kwargs: dict) -> Optional[list[str]]:
return kwargs.get("sort_by", {}).get("field") or None
diff --git a/saleor/graphql/order/tests/integration/test_bulk_order.py b/saleor/graphql/order/tests/integration/test_bulk_order.py
index bf9d0bf0c5..7ea79101e3 100644
--- a/saleor/graphql/order/tests/integration/test_bulk_order.py
+++ b/saleor/graphql/order/tests/integration/test_bulk_order.py
@@ -268,7 +268,7 @@ def test_filter_imported_orders(
response = staff_api_client.post_graphql(ORDER_BULK_CREATE, variables)
content = get_graphql_content(response)
results = content["data"]["orderBulkCreate"]["results"]
- order_1_id, order_2_id, order_3_id = [result["order"]["id"] for result in results]
+ order_1_id, order_2_id, order_3_id = (result["order"]["id"] for result in results)
# filter created orders by partially fulfilled status
query = """
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
index 3dd5a1ee6e..1865fc79dd 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
@@ -1,8 +1,8 @@
from decimal import Decimal
+from unittest import mock
from unittest.mock import ANY, patch
import graphene
-import mock
from prices import Money, TaxedMoney
from .....core.prices import quantize_price
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
index 9ea242051c..38b040f720 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
@@ -1,8 +1,8 @@
from decimal import Decimal
+from unittest import mock
from unittest.mock import ANY, patch
import graphene
-import mock
from prices import Money, TaxedMoney
from .....core.prices import quantize_price
diff --git a/saleor/graphql/order/tests/mutations/test_order_refund.py b/saleor/graphql/order/tests/mutations/test_order_refund.py
index c9e8e38237..73dde641a2 100644
--- a/saleor/graphql/order/tests/mutations/test_order_refund.py
+++ b/saleor/graphql/order/tests/mutations/test_order_refund.py
@@ -1,7 +1,7 @@
from decimal import Decimal
+from unittest.mock import patch
import graphene
-from mock import patch
from .....order import FulfillmentStatus
from .....order import events as order_events
diff --git a/saleor/graphql/order/tests/test_order_payment.py b/saleor/graphql/order/tests/test_order_payment.py
index 67debef4ca..d27f9317ce 100644
--- a/saleor/graphql/order/tests/test_order_payment.py
+++ b/saleor/graphql/order/tests/test_order_payment.py
@@ -24,19 +24,16 @@ def test_clean_payment_without_payment_associated_to_order(
assert not OrderEvent.objects.exists()
additional_arguments = ", amount: 2" if requires_amount else ""
- query = """
- mutation %(mutationName)s($id: ID!) {
- %(mutationName)s(id: $id %(args)s) {
- errors {
+ query = f"""
+ mutation {mutation_name}($id: ID!) {{
+ {mutation_name}(id: $id {additional_arguments}) {{
+ errors {{
field
message
- }
- }
- }
- """ % {
- "mutationName": mutation_name,
- "args": additional_arguments,
- }
+ }}
+ }}
+ }}
+ """
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 8b5466323d..7702a8516a 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import List, Optional
+from typing import Optional
from uuid import UUID
import graphene
@@ -641,7 +641,7 @@ class Fulfillment(ModelObjectType[models.Fulfillment]):
def _resolve_stock_warehouse(stock: Stock):
return WarehouseByIdLoader(info.context).load(stock.warehouse_id)
- def _resolve_stock(fulfillment_lines: List[models.FulfillmentLine]):
+ def _resolve_stock(fulfillment_lines: list[models.FulfillmentLine]):
try:
line = fulfillment_lines[0]
except IndexError:
@@ -2193,7 +2193,7 @@ class Order(ModelObjectType[models.Order]):
return None
@staticmethod
- def __resolve_references(roots: List["Order"], info):
+ def __resolve_references(roots: list["Order"], info):
requestor = get_user_or_app_from_context(info.context)
requestor_has_access_to_all = has_one_of_permissions(
requestor, [OrderPermissions.MANAGE_ORDERS]
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 2fb52a9d54..0e8095f468 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,6 +1,7 @@
from collections import defaultdict
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
+from typing import TYPE_CHECKING, Optional
import graphene
from django.core.exceptions import ValidationError
@@ -22,7 +23,7 @@ if TYPE_CHECKING:
from dataclasses import dataclass
-T_ERRORS = Dict[str, List[ValidationError]]
+T_ERRORS = dict[str, list[ValidationError]]
@dataclass
diff --git a/saleor/graphql/page/mutations/page_attribute_assign.py b/saleor/graphql/page/mutations/page_attribute_assign.py
index 4e23e636c1..da085dd311 100644
--- a/saleor/graphql/page/mutations/page_attribute_assign.py
+++ b/saleor/graphql/page/mutations/page_attribute_assign.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -40,9 +39,9 @@ class PageAttributeAssign(BaseMutation):
@classmethod
def clean_attributes(
cls,
- errors: Dict["str", List[ValidationError]],
+ errors: dict["str", list[ValidationError]],
page_type: "page_models.PageType",
- attr_pks: List[int],
+ attr_pks: list[int],
):
"""Ensure the attributes are page attributes and are not already assigned."""
@@ -84,7 +83,7 @@ class PageAttributeAssign(BaseMutation):
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, attribute_ids, page_type_id
):
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
# retrieve the requested page type
page_type = cls.get_node_or_error(
diff --git a/saleor/graphql/page/mutations/page_type_create.py b/saleor/graphql/page/mutations/page_type_create.py
index 2e03f65052..860ec09d32 100644
--- a/saleor/graphql/page/mutations/page_type_create.py
+++ b/saleor/graphql/page/mutations/page_type_create.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import TYPE_CHECKING, Dict, List
+from typing import TYPE_CHECKING
import graphene
from django.core.exceptions import ValidationError
@@ -36,8 +36,8 @@ class PageTypeMixin:
@classmethod
def validate_attributes(
cls,
- errors: Dict[str, List[ValidationError]],
- attributes: List["Attribute"],
+ errors: dict[str, list[ValidationError]],
+ attributes: list["Attribute"],
field: str,
):
"""All attributes must be page type attribute.
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index 7cc6be9cc8..6c0edcd32b 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta
from functools import partial
from unittest import mock
+from unittest.mock import ANY
import graphene
import pytz
@@ -8,7 +9,6 @@ from django.conf import settings
from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from freezegun import freeze_time
-from mock import ANY
from .....page.error_codes import PageErrorCode
from .....page.models import Page, PageType
diff --git a/saleor/graphql/page/tests/mutations/test_page_delete.py b/saleor/graphql/page/tests/mutations/test_page_delete.py
index f54a88304e..3bfedca83e 100644
--- a/saleor/graphql/page/tests/mutations/test_page_delete.py
+++ b/saleor/graphql/page/tests/mutations/test_page_delete.py
@@ -1,11 +1,11 @@
from functools import partial
from unittest import mock
+from unittest.mock import ANY
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
-from mock import ANY
from .....attribute.models import AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index 9bd5df3d8a..9d9abeafda 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta
from functools import partial
from unittest import mock
+from unittest.mock import ANY
import graphene
import pytest
@@ -10,7 +11,6 @@ from django.utils import timezone
from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from freezegun import freeze_time
-from mock import ANY
from .....attribute.models import AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.py
index 7f8ac13508..eb71cb9c76 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from ...attribute import models as attribute_models
@@ -92,7 +90,7 @@ class PageType(ModelObjectType[models.PageType]):
)
@staticmethod
- def __resolve_references(roots: List["PageType"], _info: ResolveInfo):
+ def __resolve_references(roots: list["PageType"], _info: ResolveInfo):
return resolve_federation_references(PageType, roots, models.PageType.objects)
diff --git a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
index 4cb67669cb..fba470127c 100644
--- a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
+++ b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -176,7 +174,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
)
@classmethod
- def validate_metadata_keys(cls, metadata_list: List[dict]):
+ def validate_metadata_keys(cls, metadata_list: list[dict]):
if metadata_contains_empty_key(metadata_list):
raise ValidationError(
{
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index c9de09d630..cf67b3cfdc 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -1,6 +1,6 @@
import uuid
from decimal import Decimal
-from typing import Dict, List, Optional, Union, cast
+from typing import Optional, Union, cast
import graphene
from django.core.exceptions import ValidationError
@@ -136,7 +136,7 @@ class TransactionCreate(BaseMutation):
@classmethod
def validate_metadata_keys( # type: ignore[override]
- cls, metadata_list: List[dict], field_name, error_code
+ cls, metadata_list: list[dict], field_name, error_code
):
if metadata_contains_empty_key(metadata_list):
raise ValidationError(
@@ -149,7 +149,7 @@ class TransactionCreate(BaseMutation):
)
@classmethod
- def get_money_data_from_input(cls, cleaned_data: dict) -> Dict[str, Decimal]:
+ def get_money_data_from_input(cls, cleaned_data: dict) -> dict[str, Decimal]:
money_data = {}
if amount_authorized := cleaned_data.pop("amount_authorized", None):
money_data["authorized_value"] = amount_authorized["amount"]
@@ -327,7 +327,7 @@ class TransactionCreate(BaseMutation):
/,
*,
id: str,
- transaction: Dict,
+ transaction: dict,
transaction_event=None,
):
order_or_checkout_instance = cls.get_node_or_error(info, id)
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
index 2c976fa21c..2dfebb9f01 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
@@ -1,6 +1,5 @@
from decimal import Decimal
-
-import mock
+from unittest import mock
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_refund.py b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
index c34df2008c..48d0bfa894 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
@@ -1,5 +1,6 @@
+from unittest.mock import patch
+
import graphene
-from mock import patch
from .....payment import TransactionKind
from .....payment.models import ChargeStatus
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index a57d28803d..11c1ea4839 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -1,8 +1,8 @@
from decimal import Decimal
+from unittest.mock import patch
import graphene
import pytest
-from mock import patch
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 4dd39e673e..308eb0acfa 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -1,6 +1,6 @@
from decimal import Decimal
+from unittest import mock
-import mock
import pytest
from .....channel import TransactionFlowStrategy
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index 114a9d062b..3a5e0cc1c5 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -1,7 +1,7 @@
from decimal import Decimal
+from unittest import mock
import graphene
-import mock
import pytest
from .....channel import TransactionFlowStrategy
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
index 8aff1dfcdf..4bcddb660a 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -1,8 +1,8 @@
from decimal import Decimal
+from unittest.mock import patch
import graphene
import pytest
-from mock import patch
from .....app.models import App
from .....order import OrderEvents
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
index 7fb400b3f0..39133b340c 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
@@ -1,7 +1,7 @@
from decimal import Decimal
+from unittest.mock import patch
import graphene
-from mock import patch
from .....payment import TransactionAction, TransactionEventType
from .....payment.interface import TransactionActionData
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 68999cf572..e9be36e12c 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -1,8 +1,8 @@
from decimal import Decimal
+from unittest.mock import patch
import graphene
import pytest
-from mock import patch
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
diff --git a/saleor/graphql/payment/utils.py b/saleor/graphql/payment/utils.py
index 90f1f5876d..b5cae00aef 100644
--- a/saleor/graphql/payment/utils.py
+++ b/saleor/graphql/payment/utils.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List, Optional
+from typing import TYPE_CHECKING, Optional
from ...payment import models as payment_models
@@ -7,7 +7,7 @@ if TYPE_CHECKING:
from ...app.models import App
-def metadata_contains_empty_key(metadata_list: List[dict]) -> bool:
+def metadata_contains_empty_key(metadata_list: list[dict]) -> bool:
return not all([data["key"].strip() for data in metadata_list])
diff --git a/saleor/graphql/plugins/filters.py b/saleor/graphql/plugins/filters.py
index 839796ed19..bc6f2dacc8 100644
--- a/saleor/graphql/plugins/filters.py
+++ b/saleor/graphql/plugins/filters.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
import graphene
@@ -10,8 +10,8 @@ from .types import Plugin
def filter_plugin_status_in_channels(
- plugins: List[Plugin], status_in_channels: dict
-) -> List[Plugin]:
+ plugins: list[Plugin], status_in_channels: dict
+) -> list[Plugin]:
is_active = status_in_channels["active"]
channels_id = status_in_channels["channels"]
channels = get_nodes(channels_id, Channel)
@@ -34,7 +34,7 @@ def filter_plugin_status_in_channels(
return filtered_plugins
-def filter_plugin_by_type(plugins: List[Plugin], type):
+def filter_plugin_by_type(plugins: list[Plugin], type):
if type == PluginConfigurationType.GLOBAL:
plugins = [plugin for plugin in plugins if plugin.global_configuration]
else:
@@ -42,7 +42,7 @@ def filter_plugin_by_type(plugins: List[Plugin], type):
return plugins
-def filter_plugin_search(plugins: List[Plugin], value: Optional[str]) -> List[Plugin]:
+def filter_plugin_search(plugins: list[Plugin], value: Optional[str]) -> list[Plugin]:
plugin_fields = ["name", "description"]
if value is not None:
return [
diff --git a/saleor/graphql/plugins/resolvers.py b/saleor/graphql/plugins/resolvers.py
index a8c42b3224..e799829528 100644
--- a/saleor/graphql/plugins/resolvers.py
+++ b/saleor/graphql/plugins/resolvers.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import Dict, List, Tuple
from ...plugins.base_plugin import BasePlugin, ConfigurationTypeField
from .filters import (
@@ -38,9 +37,9 @@ def hide_private_configuration_fields(configuration, config_structure):
def aggregate_plugins_configuration(
manager,
-) -> Tuple[Dict[str, BasePlugin], Dict[str, List[BasePlugin]]]:
- plugins_per_channel: Dict[str, List[BasePlugin]] = defaultdict(list)
- global_plugins: Dict[str, BasePlugin] = {}
+) -> tuple[dict[str, BasePlugin], dict[str, list[BasePlugin]]]:
+ plugins_per_channel: dict[str, list[BasePlugin]] = defaultdict(list)
+ global_plugins: dict[str, BasePlugin] = {}
for plugin in manager.all_plugins:
hide_private_configuration_fields(plugin.configuration, plugin.CONFIG_STRUCTURE)
diff --git a/saleor/graphql/plugins/sorters.py b/saleor/graphql/plugins/sorters.py
index e539ca9787..55495dbb01 100644
--- a/saleor/graphql/plugins/sorters.py
+++ b/saleor/graphql/plugins/sorters.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
import graphene
@@ -21,7 +21,7 @@ def sort_active_key(plugin: Plugin, sort_reverse: bool):
return not active if sort_reverse else active, name
-def sort_plugins(plugins: List["Plugin"], sort_by: Optional[dict]) -> List["Plugin"]:
+def sort_plugins(plugins: list["Plugin"], sort_by: Optional[dict]) -> list["Plugin"]:
sort_reverse = False
direction = sort_by.get("direction", OrderDirection.ASC) if sort_by else None
if direction == OrderDirection.DESC:
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
index f3707897d2..bf4b00043a 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
@@ -1,4 +1,4 @@
-from typing import Iterable
+from collections.abc import Iterable
import graphene
from django.core.exceptions import ValidationError
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py
index 99cb02d00f..4c83ddb517 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List
import graphene
from django.core.exceptions import ValidationError
@@ -52,7 +51,7 @@ class ProductVariantStocksCreate(BaseMutation):
@traced_atomic_transaction()
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
manager = get_plugin_manager_promise(info.context).get()
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
stocks = data["stocks"]
variant = cls.get_node_or_error(
info, data["variant_id"], only_type=ProductVariant
@@ -105,7 +104,7 @@ class ProductVariantStocksCreate(BaseMutation):
@classmethod
def check_for_duplicates(
- cls, warehouse_ids, errors: defaultdict[str, List[ValidationError]]
+ cls, warehouse_ids, errors: defaultdict[str, list[ValidationError]]
):
duplicates = {id for id in warehouse_ids if warehouse_ids.count(id) > 1}
error_msg = "Duplicated warehouse ID."
@@ -120,7 +119,7 @@ class ProductVariantStocksCreate(BaseMutation):
@classmethod
def update_errors(
- cls, errors: defaultdict[str, List[ValidationError]], msg, field, code, indexes
+ cls, errors: defaultdict[str, list[ValidationError]], msg, field, code, indexes
):
for index in indexes:
error = ValidationError(msg, code=code, params={"index": index})
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py
index 4e55350a0c..500a616a4d 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List
import graphene
from django.core.exceptions import ValidationError
@@ -51,7 +50,7 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
stocks = data["stocks"]
sku = data.get("sku")
variant_id = data.get("variant_id")
diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.py
index 5ce724af00..95d4cac2a9 100644
--- a/saleor/graphql/product/dataloaders/products.py
+++ b/saleor/graphql/product/dataloaders/products.py
@@ -1,5 +1,6 @@
from collections import defaultdict
-from typing import DefaultDict, Dict, Iterable, List, Optional, Tuple
+from collections.abc import Iterable
+from typing import Optional
from django.db.models import F
@@ -20,8 +21,8 @@ from ....product.models import (
)
from ...core.dataloaders import BaseThumbnailBySizeAndFormatLoader, DataLoader
-ProductIdAndChannelSlug = Tuple[int, str]
-VariantIdAndChannelSlug = Tuple[int, str]
+ProductIdAndChannelSlug = tuple[int, str]
+VariantIdAndChannelSlug = tuple[int, str]
class CategoryByIdLoader(DataLoader[int, Category]):
@@ -100,14 +101,14 @@ class ProductChannelListingByProductIdAndChannelSlugLoader(
# Split the list of keys by channel first. A typical query will only touch
# a handful of unique countries but may access thousands of product variants
# so it's cheaper to execute one query per channel.
- product_channel_listing_by_channel: DefaultDict[str, List[int]] = defaultdict(
+ product_channel_listing_by_channel: defaultdict[str, list[int]] = defaultdict(
list
)
for product_id, channel_slug in keys:
product_channel_listing_by_channel[channel_slug].append(product_id)
# For each channel execute a single query for all products.
- product_channel_listing_by_product_and_channel: DefaultDict[
+ product_channel_listing_by_product_and_channel: defaultdict[
ProductIdAndChannelSlug, Optional[ProductChannelListing]
] = defaultdict()
for channel_slug, product_ids in product_channel_listing_by_channel.items():
@@ -123,12 +124,12 @@ class ProductChannelListingByProductIdAndChannelSlugLoader(
def batch_load_channel(
self, channel_slug: str, products_ids: Iterable[int]
- ) -> Iterable[Tuple[int, Optional[ProductChannelListing]]]:
+ ) -> Iterable[tuple[int, Optional[ProductChannelListing]]]:
product_channel_listings = ProductChannelListing.objects.using(
self.database_connection_name
).filter(channel__slug=channel_slug, product_id__in=products_ids)
- product_channel_listings_map: Dict[int, ProductChannelListing] = {}
+ product_channel_listings_map: dict[int, ProductChannelListing] = {}
for product_channel_listing in product_channel_listings.iterator():
product_channel_listings_map[
product_channel_listing.product_id
@@ -150,7 +151,7 @@ class ProductTypeByIdLoader(DataLoader[int, ProductType]):
return [product_types.get(product_type_id) for product_type_id in keys]
-class MediaByProductIdLoader(DataLoader[int, List[ProductMedia]]):
+class MediaByProductIdLoader(DataLoader[int, list[ProductMedia]]):
context_key = "media_by_product"
def batch_load(self, keys):
@@ -163,7 +164,7 @@ class MediaByProductIdLoader(DataLoader[int, List[ProductMedia]]):
return [media_map[product_id] for product_id in keys]
-class ImagesByProductIdLoader(DataLoader[int, List[ProductMedia]]):
+class ImagesByProductIdLoader(DataLoader[int, list[ProductMedia]]):
context_key = "images_by_product"
def batch_load(self, keys):
@@ -187,7 +188,7 @@ class ProductVariantByIdLoader(DataLoader[int, ProductVariant]):
return [variants.get(key) for key in keys]
-class ProductVariantsByProductIdLoader(DataLoader[int, List[ProductVariant]]):
+class ProductVariantsByProductIdLoader(DataLoader[int, list[ProductVariant]]):
context_key = "productvariants_by_product"
def batch_load(self, keys):
@@ -203,11 +204,11 @@ class ProductVariantsByProductIdLoader(DataLoader[int, List[ProductVariant]]):
class ProductVariantsByProductIdAndChannel(
- DataLoader[Tuple[int, str], List[ProductVariant]]
+ DataLoader[tuple[int, str], list[ProductVariant]]
):
context_key = "productvariant_by_product_and_channel"
- def batch_load(self, keys: Iterable[Tuple[int, str]]):
+ def batch_load(self, keys: Iterable[tuple[int, str]]):
product_ids, channel_slugs = zip(*keys)
variants_filter = self.get_variants_filter(product_ids, channel_slugs)
@@ -217,7 +218,7 @@ class ProductVariantsByProductIdAndChannel(
.annotate(channel_slug=F("channel_listings__channel__slug"))
.order_by("sort_order", "sku")
)
- variant_map: DefaultDict[Tuple[int, str], List[ProductVariant]] = defaultdict(
+ variant_map: defaultdict[tuple[int, str], list[ProductVariant]] = defaultdict(
list
)
for variant in variants.iterator():
@@ -293,14 +294,14 @@ class VariantChannelListingByVariantIdAndChannelLoader(
# Split the list of keys by channel first. A typical query will only touch
# a handful of unique countries but may access thousands of product variants
# so it's cheaper to execute one query per channel.
- variant_channel_listing_by_channel: DefaultDict[str, List[int]] = defaultdict(
+ variant_channel_listing_by_channel: defaultdict[str, list[int]] = defaultdict(
list
)
for variant_id, channel in keys:
variant_channel_listing_by_channel[channel].append(variant_id)
# For each channel execute a single query for all product variants.
- variant_channel_listing_by_variant_and_channel: DefaultDict[
+ variant_channel_listing_by_variant_and_channel: defaultdict[
VariantIdAndChannelSlug, Optional[ProductVariantChannelListing]
] = defaultdict()
for channel, variant_ids in variant_channel_listing_by_channel.items():
@@ -314,7 +315,7 @@ class VariantChannelListingByVariantIdAndChannelLoader(
def batch_load_channel(
self, channel: str, variant_ids: Iterable[int]
- ) -> Iterable[Tuple[int, Optional[ProductVariantChannelListing]]]:
+ ) -> Iterable[tuple[int, Optional[ProductVariantChannelListing]]]:
filter = {
f"channel__{self.field}": channel,
"variant_id__in": variant_ids,
@@ -328,7 +329,7 @@ class VariantChannelListingByVariantIdAndChannelLoader(
.order_by("pk")
)
- variant_channel_listings_map: Dict[int, ProductVariantChannelListing] = {}
+ variant_channel_listings_map: dict[int, ProductVariantChannelListing] = {}
for variant_channel_listing in variant_channel_listings.iterator():
variant_channel_listings_map[
variant_channel_listing.variant_id
@@ -363,14 +364,14 @@ class VariantsChannelListingByProductIdAndChannelSlugLoader(
# Split the list of keys by channel first. A typical query will only touch
# a handful of unique countries but may access thousands of product variants
# so it's cheaper to execute one query per channel.
- variant_channel_listing_by_channel: DefaultDict[str, List[int]] = defaultdict(
+ variant_channel_listing_by_channel: defaultdict[str, list[int]] = defaultdict(
list
)
for product_id, channel_slug in keys:
variant_channel_listing_by_channel[channel_slug].append(product_id)
# For each channel execute a single query for all product variants.
- variant_channel_listing_by_product_and_channel: DefaultDict[
+ variant_channel_listing_by_product_and_channel: defaultdict[
ProductIdAndChannelSlug, Optional[Iterable[ProductVariantChannelListing]]
] = defaultdict()
for channel_slug, product_ids in variant_channel_listing_by_channel.items():
@@ -388,7 +389,7 @@ class VariantsChannelListingByProductIdAndChannelSlugLoader(
def batch_load_channel(
self, channel_slug: str, products_ids: Iterable[int]
- ) -> Iterable[Tuple[int, Optional[List[ProductVariantChannelListing]]]]:
+ ) -> Iterable[tuple[int, Optional[list[ProductVariantChannelListing]]]]:
variants_channel_listings = (
ProductVariantChannelListing.objects.all()
.using(self.database_connection_name)
@@ -401,8 +402,8 @@ class VariantsChannelListingByProductIdAndChannelSlugLoader(
.order_by("pk")
)
- variants_channel_listings_map: Dict[
- int, List[ProductVariantChannelListing]
+ variants_channel_listings_map: dict[
+ int, list[ProductVariantChannelListing]
] = defaultdict(list)
for variant_channel_listing in variants_channel_listings.iterator():
variants_channel_listings_map[
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 1fbe9d77bf..a4b8e9ea7a 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -1,7 +1,7 @@
import datetime
import math
from collections import defaultdict
-from typing import DefaultDict, Dict, List, Optional, TypedDict
+from typing import Optional, TypedDict
import django_filters
import graphene
@@ -89,7 +89,7 @@ from .enums import (
StockAvailability,
)
-T_PRODUCT_FILTER_QUERIES = Dict[int, List[int]]
+T_PRODUCT_FILTER_QUERIES = dict[int, list[int]]
def _clean_product_attributes_filter_input(filter_value, queries):
@@ -98,9 +98,9 @@ def _clean_product_attributes_filter_input(filter_value, queries):
for attr_slug, val_slugs in filter_value:
attribute_slugs.append(attr_slug)
value_slugs.extend(val_slugs)
- attributes_slug_pk_map: Dict[str, int] = {}
- attributes_pk_slug_map: Dict[int, str] = {}
- values_map: Dict[str, Dict[str, int]] = defaultdict(dict)
+ attributes_slug_pk_map: dict[str, int] = {}
+ attributes_pk_slug_map: dict[int, str] = {}
+ values_map: dict[str, dict[str, int]] = defaultdict(dict)
for attr_slug, attr_pk in Attribute.objects.filter(
slug__in=attribute_slugs
).values_list("slug", "id"):
@@ -121,7 +121,7 @@ def _clean_product_attributes_filter_input(filter_value, queries):
# attributes are keys and values are grouped in lists
for attr_name, val_slugs in filter_value:
if attr_name not in attributes_slug_pk_map:
- raise ValueError("Unknown attribute name: %r" % (attr_name,))
+ raise ValueError(f"Unknown attribute name: {attr_name}")
attr_pk = attributes_slug_pk_map[attr_name]
attr_val_pk = [
values_map[attr_name][val_slug]
@@ -141,8 +141,8 @@ def _clean_product_attributes_range_filter_input(filter_value, queries):
.select_related("attribute")
)
- attributes_map: Dict[str, int] = {}
- values_map: DefaultDict[str, DefaultDict[str, List[int]]] = defaultdict(
+ attributes_map: dict[str, int] = {}
+ values_map: defaultdict[str, defaultdict[str, list[int]]] = defaultdict(
lambda: defaultdict(list)
)
for value_data in values.values_list(
@@ -154,7 +154,7 @@ def _clean_product_attributes_range_filter_input(filter_value, queries):
for attr_name, val_range in filter_value:
if attr_name not in attributes_map:
- raise ValueError("Unknown numeric attribute name: %r" % (attr_name,))
+ raise ValueError(f"Unknown numeric attribute name: {attr_name}")
gte, lte = val_range.get("gte", 0), val_range.get("lte", math.inf)
attr_pk = attributes_map[attr_name]
attr_values = values_map[attr_name]
@@ -190,7 +190,7 @@ def _clean_product_attributes_date_time_range_filter_input(filter_value):
class KeyValueDict(TypedDict):
pk: int
- values: Dict[Optional[bool], int]
+ values: dict[Optional[bool], int]
def _clean_product_attributes_boolean_filter_input(filter_value, queries):
@@ -198,7 +198,7 @@ def _clean_product_attributes_boolean_filter_input(filter_value, queries):
attributes = Attribute.objects.filter(
input_type=AttributeInputType.BOOLEAN, slug__in=attribute_slugs
).prefetch_related("values")
- values_map: Dict[str, KeyValueDict] = {
+ values_map: dict[str, KeyValueDict] = {
attr.slug: {
"pk": attr.pk,
"values": {val.boolean: val.pk for val in attr.values.all()},
@@ -283,7 +283,7 @@ def filter_products_by_attributes(
date_range_list,
date_time_range_list,
):
- queries: Dict[int, List[int]] = defaultdict(list)
+ queries: dict[int, list[int]] = defaultdict(list)
try:
if filter_values:
_clean_product_attributes_filter_input(filter_values, queries)
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 81e658c35c..0ac5e56b56 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -1,5 +1,4 @@
from collections import Counter, defaultdict
-from typing import DefaultDict, List
import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
@@ -117,7 +116,7 @@ class ProductAttributeAssign(BaseMutation, VariantAssignmentValidationMixin):
@classmethod
def get_operations(
- cls, info: ResolveInfo, operations: List[ProductAttributeAssignInput]
+ cls, info: ResolveInfo, operations: list[ProductAttributeAssignInput]
):
"""Resolve all passed global ids into integer PKs of the Attribute type."""
product_attrs_pks = []
@@ -277,7 +276,7 @@ class ProductAttributeAssign(BaseMutation, VariantAssignmentValidationMixin):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
product_type_id: str = data["product_type_id"]
- operations: List[ProductAttributeAssignInput] = data["operations"]
+ operations: list[ProductAttributeAssignInput] = data["operations"]
# Retrieve the requested product type
product_type: models.ProductType = graphene.Node.get_node_from_global_id(
info, product_type_id, only_type=ProductType
@@ -339,7 +338,7 @@ class ProductAttributeUnassign(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
product_type_id: str = data["product_type_id"]
- attribute_ids: List[str] = data["attribute_ids"]
+ attribute_ids: list[str] = data["attribute_ids"]
# Retrieve the requested product type
product_type = graphene.Node.get_node_from_global_id(
info, product_type_id, only_type=ProductType
@@ -388,7 +387,7 @@ class ProductAttributeAssignmentUpdate(BaseMutation, VariantAssignmentValidation
@classmethod
def get_operations(
- cls, info: ResolveInfo, operations: List[ProductAttributeAssignmentUpdateInput]
+ cls, info: ResolveInfo, operations: list[ProductAttributeAssignmentUpdateInput]
):
variant_attrs_pks = []
for operation in operations:
@@ -472,7 +471,7 @@ class ProductAttributeAssignmentUpdate(BaseMutation, VariantAssignmentValidation
@classmethod
def clean_operations(cls, product_type, variant_attrs_data):
- errors: DefaultDict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
variant_attrs_pks = [pk for pk, _ in variant_attrs_data]
cls.check_for_duplicates(errors, variant_attrs_pks)
@@ -528,7 +527,7 @@ class ProductAttributeAssignmentUpdate(BaseMutation, VariantAssignmentValidation
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
product_type_id: str = data["product_type_id"]
- operations: List[ProductAttributeAssignmentUpdateInput] = data["operations"]
+ operations: list[ProductAttributeAssignmentUpdateInput] = data["operations"]
# Retrieve the requested product type
product_type: models.ProductType = graphene.Node.get_node_from_global_id(
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index b445e8a3e9..1576c7355a 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from datetime import datetime
-from typing import TYPE_CHECKING, DefaultDict, Dict, List
+from typing import TYPE_CHECKING
import graphene
import pytz
@@ -53,7 +53,7 @@ if TYPE_CHECKING:
from ....channel.models import Channel as ChannelModel
from ....product.models import Collection as CollectionModel
-ErrorType = DefaultDict[str, List[ValidationError]]
+ErrorType = defaultdict[str, list[ValidationError]]
class PublishableChannelListingInput(BaseInputObjectType):
@@ -156,8 +156,8 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
@classmethod
def clean_available_for_purchase(cls, cleaned_input, errors: ErrorType):
- channels_with_invalid_available_for_purchase: List[str] = []
- channels_with_invalid_date: List[str] = []
+ channels_with_invalid_available_for_purchase: list[str] = []
+ channels_with_invalid_date: list[str] = []
for update_channel in cleaned_input.get("update_channels", []):
is_available_for_purchase = update_channel.get("is_available_for_purchase")
available_for_purchase_date = update_channel.get(
@@ -235,7 +235,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
)
@classmethod
- def update_channels(cls, product: "ProductModel", update_channels: List[Dict]):
+ def update_channels(cls, product: "ProductModel", update_channels: list[dict]):
for update_channel in update_channels:
channel = update_channel["channel"]
add_variants = update_channel.get("add_variants", None)
@@ -284,7 +284,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
errors["addVariants"].append(error)
@classmethod
- def add_variants(cls, channel, add_variants: List[Dict]):
+ def add_variants(cls, channel, add_variants: list[dict]):
if not add_variants:
return
variants = cls.get_nodes_or_error(add_variants, "id", ProductVariant)
@@ -313,7 +313,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
product_channel_listing,
product,
channel,
- remove_variants: List[Dict],
+ remove_variants: list[dict],
):
if not remove_variants:
return
@@ -340,7 +340,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
CheckoutLine.objects.filter(id__in=lines_ids).delete()
@classmethod
- def remove_channels(cls, product: "ProductModel", remove_channels: List[Dict]):
+ def remove_channels(cls, product: "ProductModel", remove_channels: list[dict]):
ProductChannelListing.objects.filter(
product=product, channel_id__in=remove_channels
).delete()
@@ -351,7 +351,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
cls.perform_checkout_lines_delete(variant_ids, remove_channels)
@classmethod
- def save(cls, info: ResolveInfo, product: "ProductModel", cleaned_input: Dict):
+ def save(cls, info: ResolveInfo, product: "ProductModel", cleaned_input: dict):
with traced_atomic_transaction():
cls.update_channels(product, cleaned_input.get("update_channels", []))
cls.remove_channels(product, cleaned_input.get("remove_channels", []))
@@ -365,7 +365,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
cls, _root, info: ResolveInfo, /, *, id, input
):
product = cls.get_node_or_error(info, id, only_type=Product, field="id")
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
cleaned_input = cls.clean_channels(
info,
@@ -434,7 +434,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
error_type_field = "product_channel_listing_errors"
@classmethod
- def clean_channels(cls, info: ResolveInfo, input, errors: ErrorType) -> List:
+ def clean_channels(cls, info: ResolveInfo, input, errors: ErrorType) -> list:
add_channels_ids = [
channel_listing_data["channel_id"] for channel_listing_data in input
]
@@ -450,7 +450,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
)
)
else:
- channels: List["ChannelModel"] = []
+ channels: list["ChannelModel"] = []
if add_channels_ids:
channels = cls.get_nodes_or_error(
add_channels_ids, "channel_id", Channel
@@ -462,7 +462,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
@classmethod
def validate_product_assigned_to_channel(
- cls, variant: "ProductVariantModel", cleaned_input: List, errors: ErrorType
+ cls, variant: "ProductVariantModel", cleaned_input: list, errors: ErrorType
):
channel_pks = [
channel_listing_data["channel"].pk for channel_listing_data in cleaned_input
@@ -503,7 +503,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
errors[field_name].append(error)
@classmethod
- def clean_prices(cls, info: ResolveInfo, cleaned_input, errors: ErrorType) -> List:
+ def clean_prices(cls, info: ResolveInfo, cleaned_input, errors: ErrorType) -> list:
for channel_listing_data in cleaned_input:
price = channel_listing_data.get("price")
cost_price = channel_listing_data.get("cost_price")
@@ -517,7 +517,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
@classmethod
def save(
- cls, info: ResolveInfo, variant: "ProductVariantModel", cleaned_input: List
+ cls, info: ResolveInfo, variant: "ProductVariantModel", cleaned_input: list
):
with traced_atomic_transaction():
for channel_listing_data in cleaned_input:
@@ -569,7 +569,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
}
)
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
cleaned_input = cls.clean_channels(info, input, errors)
cls.validate_product_assigned_to_channel(variant, cleaned_input, errors)
@@ -623,7 +623,7 @@ class CollectionChannelListingUpdate(BaseChannelListingMutation):
error_type_field = "collection_channel_listing_errors"
@classmethod
- def add_channels(cls, collection: "CollectionModel", add_channels: List[Dict]):
+ def add_channels(cls, collection: "CollectionModel", add_channels: list[dict]):
for add_channel in add_channels:
defaults = {}
for field in ["is_published", "published_at"]:
@@ -634,14 +634,14 @@ class CollectionChannelListingUpdate(BaseChannelListingMutation):
)
@classmethod
- def remove_channels(cls, collection: "CollectionModel", remove_channels: List[int]):
+ def remove_channels(cls, collection: "CollectionModel", remove_channels: list[int]):
CollectionChannelListing.objects.filter(
collection=collection, channel_id__in=remove_channels
).delete()
@classmethod
def save(
- cls, info: ResolveInfo, collection: "CollectionModel", cleaned_input: Dict
+ cls, info: ResolveInfo, collection: "CollectionModel", cleaned_input: dict
):
with traced_atomic_transaction():
cls.add_channels(collection, cleaned_input.get("add_channels", []))
@@ -652,7 +652,7 @@ class CollectionChannelListingUpdate(BaseChannelListingMutation):
cls, _root, info: ResolveInfo, /, *, id, input
):
collection = cls.get_node_or_error(info, id, only_type=Collection, field="id")
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
cleaned_input = cls.clean_channels(
info,
diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.py
index 21e89fab88..65ea1737c8 100644
--- a/saleor/graphql/product/mutations/product/product_create.py
+++ b/saleor/graphql/product/mutations/product/product_create.py
@@ -1,5 +1,3 @@
-from typing import List, Tuple
-
import graphene
from django.core.exceptions import ValidationError
@@ -122,7 +120,7 @@ class ProductCreateInput(ProductInput):
doc_category = DOC_CATEGORY_PRODUCTS
-T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]
+T_INPUT_MAP = list[tuple[attribute_models.Attribute, AttrValuesInput]]
class ProductCreate(ModelMutation):
diff --git a/saleor/graphql/product/mutations/product/product_update.py b/saleor/graphql/product/mutations/product/product_update.py
index e1e2b69d00..9e563dddc1 100644
--- a/saleor/graphql/product/mutations/product/product_update.py
+++ b/saleor/graphql/product/mutations/product/product_update.py
@@ -1,5 +1,3 @@
-from typing import List, Tuple
-
import graphene
from .....attribute import models as attribute_models
@@ -15,7 +13,7 @@ from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import Product
from .product_create import ProductCreate, ProductInput
-T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]
+T_INPUT_MAP = list[tuple[attribute_models.Attribute, AttrValuesInput]]
class ProductUpdate(ProductCreate, ModelWithExtRefMutation):
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
index 37cd1247be..45f81c85df 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List, Tuple
import graphene
from django.core.exceptions import ValidationError
@@ -35,7 +34,7 @@ from ...utils import (
)
from ..product.product_create import StockInput
-T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]
+T_INPUT_MAP = list[tuple[attribute_models.Attribute, AttrValuesInput]]
class PreorderSettingsInput(BaseInputObjectType):
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
index 0d675ad01d..53871d2714 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List, Tuple
import graphene
from django.core.exceptions import ValidationError
@@ -20,7 +19,7 @@ from ...types import ProductVariant
from ...utils import get_used_attribute_values_for_variant
from .product_variant_create import ProductVariantCreate, ProductVariantInput
-T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]
+T_INPUT_MAP = list[tuple[attribute_models.Attribute, AttrValuesInput]]
class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):
diff --git a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
index 3d89dea9e5..f083da9dca 100644
--- a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
+++ b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
@@ -10,10 +10,8 @@ from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_create.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_create.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
def test_product_variants_stocks_create(
@@ -93,10 +91,8 @@ def test_product_variants_stocks_create(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_create.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_create.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
def test_product_variants_stocks_create_with_single_webhook_called(
@@ -298,10 +294,8 @@ PRODUCT_VARIANT_STOCKS_DELETE_MUTATION = """
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_product_variants_stocks_delete_by_id(
@@ -359,10 +353,8 @@ def test_product_variants_stocks_delete_by_id(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_product_variants_stocks_delete_by_sku(
@@ -419,10 +411,8 @@ def test_product_variants_stocks_delete_by_sku(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_product_variants_stocks_delete_with_out_of_stock_webhook_many_calls(
diff --git a/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py
index 591d320457..fe131d89c9 100644
--- a/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py
@@ -61,10 +61,8 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
@patch(
- (
- "saleor.graphql.product.bulk_mutations.product_variant_bulk_create."
- "get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations.product_variant_bulk_create."
+ "get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_product_variant_bulk_create_by_name(
@@ -122,10 +120,8 @@ def test_product_variant_bulk_create_by_name(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_create.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_create.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_product_variant_bulk_create_by_attribute_id(
diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
index d516f5842a..d609930307 100644
--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -1513,10 +1513,8 @@ def test_product_bulk_create_with_variants_and_invalid_stock(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_bulk_create.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_bulk_create.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.channel_updated")
def test_product_bulk_create_with_variants_and_channel_listings(
diff --git a/saleor/graphql/product/tests/mutations/test_product_delete.py b/saleor/graphql/product/tests/mutations/test_product_delete.py
index befded09f2..87a95a58df 100644
--- a/saleor/graphql/product/tests/mutations/test_product_delete.py
+++ b/saleor/graphql/product/tests/mutations/test_product_delete.py
@@ -1,11 +1,10 @@
from functools import partial
-from unittest.mock import patch
+from unittest.mock import ANY, patch
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
-from mock import ANY
from prices import Money, TaxedMoney
from .....attribute.models import AttributeValue
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
index c8fe750571..58e53eb9ce 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
@@ -100,10 +100,8 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_create.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_create.get_webhooks_for_event"
)
@patch(
"saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
@@ -183,10 +181,8 @@ def test_product_variant_bulk_create_by_name(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_create.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_create.get_webhooks_for_event"
)
@patch(
"saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
index f626be1bf4..01c57921a5 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
@@ -68,10 +68,8 @@ PRODUCT_VARIANT_BULK_UPDATE_MUTATION = """
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_update.get_webhooks_for_event"
)
@patch(
"saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
@@ -137,10 +135,8 @@ def test_product_variant_bulk_update(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_update.get_webhooks_for_event"
)
@patch(
"saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py
index f506858295..9cc2110bd3 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py
@@ -244,10 +244,8 @@ def test_update_or_create_variant_stocks(variant, warehouses):
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_update.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@@ -304,10 +302,8 @@ def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_update.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@@ -353,10 +349,8 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_update.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@@ -404,10 +398,8 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_update.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@@ -453,10 +445,8 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_update.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
@@ -502,10 +492,8 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_stocks_update.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_stocks_update.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
diff --git a/saleor/graphql/product/tests/queries/test_product_type_query.py b/saleor/graphql/product/tests/queries/test_product_type_query.py
index 5225771452..124eecbf1e 100644
--- a/saleor/graphql/product/tests/queries/test_product_type_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_type_query.py
@@ -412,12 +412,10 @@ def test_product_type_get_unassigned_product_type_attributes(
unassigned_attributes
), gql_unassigned_attributes
- received_ids = sorted((attr["node"]["id"] for attr in gql_unassigned_attributes))
+ received_ids = sorted(attr["node"]["id"] for attr in gql_unassigned_attributes)
expected_ids = sorted(
- (
- graphene.Node.to_global_id("Attribute", attr.pk)
- for attr in unassigned_attributes
- )
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in unassigned_attributes
)
assert received_ids == expected_ids
diff --git a/saleor/graphql/product/tests/queries/test_variant_query.py b/saleor/graphql/product/tests/queries/test_variant_query.py
index 18ec150316..2e7edab247 100644
--- a/saleor/graphql/product/tests/queries/test_variant_query.py
+++ b/saleor/graphql/product/tests/queries/test_variant_query.py
@@ -626,13 +626,13 @@ def test_variant_restricted_fields_permissions(
is_nested,
channel_USD,
):
- query = """
- query ProductVariant($id: ID!, $channel: String) {
- productVariant(id: $id, channel: $channel) {
- %(field)s
- }
- }
- """ % {"field": field if not is_nested else "%s { __typename }" % field}
+ query = f"""
+ query ProductVariant($id: ID!, $channel: String) {{
+ productVariant(id: $id, channel: $channel) {{
+ {field if not is_nested else f"{field} {{ __typename }}"}
+ }}
+ }}
+ """
variant = product.variants.first()
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant.pk),
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 4d97a0c0f9..3552ab1703 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -373,10 +373,8 @@ def test_delete_collections_with_images(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "collection_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "collection_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.collection_deleted")
def test_delete_collections_trigger_collection_deleted_webhook(
@@ -412,10 +410,8 @@ def test_delete_collections_trigger_collection_deleted_webhook(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "collection_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "collection_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_delete_collections_trigger_product_updated_webhook(
@@ -606,10 +602,8 @@ def test_delete_products_with_images(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -646,10 +640,8 @@ def test_delete_products_trigger_webhook(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_delete_products_without_variants(
@@ -945,9 +937,7 @@ mutation productVariantBulkDelete($skus: [String!]!) {
@patch(
- (
- "saleor.graphql.product.bulk_mutations.product_variant_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations.product_variant_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -998,10 +988,8 @@ def test_delete_product_variants_by_sku(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_delete.get_webhooks_for_event"
)
@patch(
"saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
@@ -1067,10 +1055,8 @@ mutation productVariantBulkDelete($ids: [ID!]!) {
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -1123,10 +1109,8 @@ def test_delete_product_variants(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_delete.get_webhooks_for_event"
)
@patch(
"saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
@@ -1255,10 +1239,8 @@ def test_delete_product_variants_removes_checkout_lines(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.product.signals.delete_from_storage_task")
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@@ -1488,10 +1470,8 @@ def test_product_delete_removes_reference_to_page(
@patch(
- (
- "saleor.graphql.product.bulk_mutations."
- "product_variant_bulk_delete.get_webhooks_for_event"
- )
+ "saleor.graphql.product.bulk_mutations."
+ "product_variant_bulk_delete.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.py
index f28a361963..f81fbecb4d 100644
--- a/saleor/graphql/product/types/categories.py
+++ b/saleor/graphql/product/types/categories.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
import graphene
from graphene import relay
@@ -193,7 +193,7 @@ class Category(ModelObjectType[models.Category]):
return create_connection_slice(qs, info, kwargs, ProductCountableConnection)
@staticmethod
- def __resolve_references(roots: List["Category"], _info):
+ def __resolve_references(roots: list["Category"], _info):
return resolve_federation_references(Category, roots, models.Category.objects)
diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.py
index ecc3d728dd..9a7045eea0 100644
--- a/saleor/graphql/product/types/channels.py
+++ b/saleor/graphql/product/types/channels.py
@@ -1,6 +1,6 @@
from dataclasses import asdict
from decimal import Decimal
-from typing import List, Optional
+from typing import Optional
import graphene
from promise import Promise
@@ -151,7 +151,7 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
def calculate_margin_with_variants(variants):
def calculate_margin_with_channel(channel):
def calculate_margin_with_channel_listings(
- variant_channel_listings: List[
+ variant_channel_listings: list[
Optional[models.ProductVariantChannelListing]
],
):
@@ -190,7 +190,7 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
def calculate_margin_with_variants(variants):
def calculate_margin_with_channel(channel):
def calculate_margin_with_channel_listings(
- variant_channel_listings: List[
+ variant_channel_listings: list[
Optional[models.ProductVariantChannelListing]
],
):
diff --git a/saleor/graphql/product/types/collections.py b/saleor/graphql/product/types/collections.py
index e8ddb5595f..812cdda2f8 100644
--- a/saleor/graphql/product/types/collections.py
+++ b/saleor/graphql/product/types/collections.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import List, Optional
+from typing import Optional
import graphene
from graphene import relay
@@ -168,7 +168,7 @@ class Collection(ChannelContextTypeWithMetadata[models.Collection]):
return description if description is not None else {}
@staticmethod
- def __resolve_references(roots: List["Collection"], info: ResolveInfo):
+ def __resolve_references(roots: list["Collection"], info: ResolveInfo):
from ..resolvers import resolve_collections
channels = defaultdict(set)
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 9fdfaad7f3..d0206c6c4a 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -2,7 +2,7 @@ import sys
from collections import defaultdict
from dataclasses import asdict
from decimal import Decimal
-from typing import List, Optional
+from typing import Optional
import graphene
from graphene import relay
@@ -791,7 +791,7 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):
return variant_channel_listings.then(calculate_global_sold_units)
@staticmethod
- def __resolve_references(roots: List["ProductVariant"], info):
+ def __resolve_references(roots: list["ProductVariant"], info):
requestor = get_user_or_app_from_context(info.context)
requestor_has_access_to_all = has_one_of_permissions(
requestor, ALL_PRODUCTS_PERMISSIONS
@@ -1269,7 +1269,7 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):
@staticmethod
def resolve_attribute(root: ChannelContext[models.Product], info, slug):
def get_selected_attribute_by_slug(
- attributes: List[SelectedAttribute],
+ attributes: list[SelectedAttribute],
) -> Optional[SelectedAttribute]:
return next(
(atr for atr in attributes if atr["attribute"].slug == slug),
@@ -1551,7 +1551,7 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):
return ProductChargeTaxesByTaxClassIdLoader(info.context).load(tax_class_id)
@staticmethod
- def __resolve_references(roots: List["Product"], info):
+ def __resolve_references(roots: list["Product"], info):
requestor = get_user_or_app_from_context(info.context)
channels = defaultdict(set)
roots_ids = []
@@ -1779,7 +1779,7 @@ class ProductType(ModelObjectType[models.ProductType]):
)
@staticmethod
- def __resolve_references(roots: List["ProductType"], _info):
+ def __resolve_references(roots: list["ProductType"], _info):
return resolve_federation_references(
ProductType, roots, models.ProductType.objects
)
@@ -1846,7 +1846,7 @@ class ProductMedia(ModelObjectType[models.ProductMedia]):
)
@staticmethod
- def __resolve_references(roots: List["ProductMedia"], _info):
+ def __resolve_references(roots: list["ProductMedia"], _info):
return resolve_federation_references(
ProductMedia, roots, models.ProductMedia.objects
)
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index 5ff678ad54..aab79bcc40 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -1,5 +1,6 @@
from collections import defaultdict, namedtuple
-from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional
import graphene
from django.core.exceptions import ValidationError
@@ -73,7 +74,7 @@ def get_used_variants_attribute_values(product):
@traced_atomic_transaction()
def create_stocks(
variant: "ProductVariant",
- stocks_data: List[Dict[str, str]],
+ stocks_data: list[dict[str, str]],
warehouses: Iterable["Warehouse"],
):
try:
@@ -104,8 +105,8 @@ def get_draft_order_lines_data_for_variants(
lines = order_models.OrderLine.objects.filter(
variant__id__in=variant_ids, order__status=OrderStatus.DRAFT
).select_related("order")
- order_to_lines_mapping: Dict[
- order_models.Order, List[order_models.OrderLine]
+ order_to_lines_mapping: dict[
+ order_models.Order, list[order_models.OrderLine]
] = defaultdict(list)
line_pks = set()
order_pks = set()
@@ -151,7 +152,7 @@ def search_string_in_kwargs(kwargs: dict) -> bool:
return bool(filter_search.strip()) or bool(search.strip())
-def sort_field_from_kwargs(kwargs: dict) -> Optional[List[str]]:
+def sort_field_from_kwargs(kwargs: dict) -> Optional[list[str]]:
return kwargs.get("sort_by", {}).get("field") or None
@@ -160,10 +161,8 @@ def check_for_sorting_by_rank(info, kwargs: dict):
# sort by RANK can be used only with search filter
if not search_string_in_kwargs(kwargs):
raise GraphQLError(
- (
- "Sorting by RANK is available only when using a search filter "
- "or search argument."
- )
+ "Sorting by RANK is available only when using a search filter "
+ "or search argument."
)
if search_string_in_kwargs(kwargs) and not sort_field_from_kwargs(kwargs):
# default to sorting by RANK if search is used
diff --git a/saleor/graphql/schema_printer.py b/saleor/graphql/schema_printer.py
index 24f375dc7f..c4c5b10d71 100644
--- a/saleor/graphql/schema_printer.py
+++ b/saleor/graphql/schema_printer.py
@@ -3,7 +3,7 @@
Can be dropped once we upgrade from the legacy version of GraphQL Core.
"""
-from typing import Callable, Dict, List, Optional, Union, cast
+from typing import Callable, Optional, Union, cast
from graphene.types.definitions import GrapheneObjectType
from graphql.language.printer import print_ast
@@ -63,7 +63,7 @@ def print_filtered_schema(
) -> str:
directives = filter(directive_filter, schema.get_directives())
types = filter(
- type_filter, cast(List[GraphQLNamedType], schema.get_type_map().values())
+ type_filter, cast(list[GraphQLNamedType], schema.get_type_map().values())
)
return "\n\n".join(
@@ -296,11 +296,11 @@ def print_fields(
return print_block(fields)
-def print_block(items: List[str]) -> str:
+def print_block(items: list[str]) -> str:
return " {\n" + "\n".join(items) + "\n}" if items else ""
-def print_args(args: Dict[str, GraphQLArgument], indentation: str = "") -> str:
+def print_args(args: dict[str, GraphQLArgument], indentation: str = "") -> str:
if not args:
return ""
diff --git a/saleor/graphql/shipping/mutations/base.py b/saleor/graphql/shipping/mutations/base.py
index 805c5aec44..041630c914 100644
--- a/saleor/graphql/shipping/mutations/base.py
+++ b/saleor/graphql/shipping/mutations/base.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -27,7 +26,7 @@ from ..types import ShippingMethodPostalCodeRule, ShippingMethodType
class ShippingZoneMixin:
@classmethod
def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
cls.check_duplicates(
errors, data, "add_warehouses", "remove_warehouses", "warehouses"
)
@@ -286,7 +285,7 @@ class ShippingPriceMixin:
cleaned_input = super().clean_input( # type: ignore[misc] # mixin
info, instance, data, **kwargs
)
- errors: Dict[str, ValidationError] = {}
+ errors: dict[str, ValidationError] = {}
cls.clean_weight(cleaned_input, errors)
if (
"minimum_delivery_days" in cleaned_input
diff --git a/saleor/graphql/shipping/mutations/shipping_method_channel_listing_update.py b/saleor/graphql/shipping/mutations/shipping_method_channel_listing_update.py
index 670287c564..ff0612aedb 100644
--- a/saleor/graphql/shipping/mutations/shipping_method_channel_listing_update.py
+++ b/saleor/graphql/shipping/mutations/shipping_method_channel_listing_update.py
@@ -1,5 +1,5 @@
from collections import defaultdict
-from typing import TYPE_CHECKING, DefaultDict, Dict, List
+from typing import TYPE_CHECKING
import graphene
from django.core.exceptions import ValidationError
@@ -25,7 +25,7 @@ from ..utils import get_shipping_model_by_object_id
if TYPE_CHECKING:
from ....shipping.models import ShippingMethod as ShippingMethodModel
-ErrorType = DefaultDict[str, List[ValidationError]]
+ErrorType = defaultdict[str, list[ValidationError]]
class ShippingMethodChannelListingAddInput(BaseInputObjectType):
@@ -85,7 +85,7 @@ class ShippingMethodChannelListingUpdate(BaseChannelListingMutation):
@classmethod
def add_channels(
- cls, shipping_method: "ShippingMethodModel", add_channels: List[Dict]
+ cls, shipping_method: "ShippingMethodModel", add_channels: list[dict]
):
for add_channel in add_channels:
channel = add_channel["channel"]
@@ -108,7 +108,7 @@ class ShippingMethodChannelListingUpdate(BaseChannelListingMutation):
@classmethod
def remove_channels(
- cls, shipping_method: "ShippingMethodModel", remove_channels: List[int]
+ cls, shipping_method: "ShippingMethodModel", remove_channels: list[int]
):
ShippingMethodChannelListing.objects.filter(
shipping_method=shipping_method, channel_id__in=remove_channels
@@ -122,7 +122,7 @@ class ShippingMethodChannelListingUpdate(BaseChannelListingMutation):
cls,
info: ResolveInfo,
shipping_method: "ShippingMethodModel",
- cleaned_input: Dict,
+ cleaned_input: dict,
):
# transaction ensures consistent channels data
with traced_atomic_transaction():
@@ -261,7 +261,7 @@ class ShippingMethodChannelListingUpdate(BaseChannelListingMutation):
):
shipping_method = get_shipping_model_by_object_id(id)
- errors: defaultdict[str, List[ValidationError]] = defaultdict(list)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
clean_channels = cls.clean_channels(
info, input, errors, ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
)
diff --git a/saleor/graphql/shipping/utils.py b/saleor/graphql/shipping/utils.py
index 5a1694a54c..688764d44a 100644
--- a/saleor/graphql/shipping/utils.py
+++ b/saleor/graphql/shipping/utils.py
@@ -1,4 +1,5 @@
-from typing import Iterable, List, Optional, overload
+from collections.abc import Iterable
+from typing import Optional, overload
from django.core.exceptions import ValidationError
@@ -34,7 +35,7 @@ def get_shipping_model_by_object_id(object_id, raise_error=True):
return None
-def get_instances_by_object_ids(object_ids: List[str]) -> Iterable[ShippingMethod]:
+def get_instances_by_object_ids(object_ids: list[str]) -> Iterable[ShippingMethod]:
model_ids = []
for object_id in object_ids:
_, object_pk = from_global_id_or_error(object_id)
diff --git a/saleor/graphql/tax/dataloaders.py b/saleor/graphql/tax/dataloaders.py
index 84e2d05508..0d872014a5 100644
--- a/saleor/graphql/tax/dataloaders.py
+++ b/saleor/graphql/tax/dataloaders.py
@@ -1,6 +1,5 @@
from collections import defaultdict
from decimal import Decimal
-from typing import List
from django.db.models import Exists, OuterRef
from promise import Promise
@@ -45,7 +44,7 @@ class TaxConfigurationByChannelId(DataLoader[int, TaxConfiguration]):
return [tax_configs[key] for key in keys]
-class TaxClassCountryRateByTaxClassIDLoader(DataLoader[int, List[TaxClassCountryRate]]):
+class TaxClassCountryRateByTaxClassIDLoader(DataLoader[int, list[TaxClassCountryRate]]):
context_key = "tax_class_country_rate_by_tax_class_id"
def batch_load(self, keys):
diff --git a/saleor/graphql/translations/mutations/utils.py b/saleor/graphql/translations/mutations/utils.py
index 40594748a6..d5d6df070b 100644
--- a/saleor/graphql/translations/mutations/utils.py
+++ b/saleor/graphql/translations/mutations/utils.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import Tuple, Type
import graphene
from django.core.exceptions import ImproperlyConfigured, ValidationError
@@ -67,7 +66,7 @@ TRANSLATABLE_CONTENT_TO_MODEL = {
}
-def validate_input_against_model(model: Type[Model], input_data: dict):
+def validate_input_against_model(model: type[Model], input_data: dict):
data_to_validate = {key: value for key, value in input_data.items() if value}
instance = model(**data_to_validate)
all_fields = [field.name for field in model._meta.fields]
@@ -80,7 +79,7 @@ class BaseTranslateMutation(ModelMutation):
abstract = True
@classmethod
- def clean_node_id(cls, id: str) -> Tuple[str, Type[graphene.ObjectType]]:
+ def clean_node_id(cls, id: str) -> tuple[str, type[graphene.ObjectType]]:
if not id:
raise ValidationError(
{"id": ValidationError("This field is required", code="required")}
diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.py
index bddbceedfe..ab8e3d1857 100644
--- a/saleor/graphql/translations/schema.py
+++ b/saleor/graphql/translations/schema.py
@@ -61,7 +61,7 @@ class TranslatableItem(graphene.Union):
elif instance_type in TYPES_TRANSLATIONS_MAP:
return TYPES_TRANSLATIONS_MAP[instance_type]
- return super(TranslatableItem, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
class TranslatableItemConnection(CountableConnection):
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index 6d11bf3ae7..5d53b76f29 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -1,12 +1,11 @@
import json
from functools import partial
-from unittest.mock import patch
+from unittest.mock import ANY, patch
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
-from mock import ANY
from ....attribute.utils import associate_attribute_values_to_instance
from ....discount.error_codes import DiscountErrorCode
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index 79469cee18..63187fafb4 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -1,4 +1,4 @@
-from typing import List, TypeVar
+from typing import TypeVar
import graphene
from django.conf import settings
@@ -36,12 +36,12 @@ from ..product.dataloaders import (
from .fields import TranslationField
-def get_translatable_attribute_values(attributes: list) -> List[AttributeValue]:
+def get_translatable_attribute_values(attributes: list) -> list[AttributeValue]:
"""Filter the list of passed attributes.
Return those which are translatable attributes.
"""
- translatable_values: List[AttributeValue] = []
+ translatable_values: list[AttributeValue] = []
for assignment in attributes:
attr = assignment["attribute"]
if attr.input_type in AttributeInputType.TRANSLATABLE_ATTRIBUTES:
diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.py
index 31987f577a..54d851f410 100644
--- a/saleor/graphql/utils/__init__.py
+++ b/saleor/graphql/utils/__init__.py
@@ -1,7 +1,8 @@
import hashlib
import logging
import traceback
-from typing import TYPE_CHECKING, Any, Dict, Iterable, Union
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Any, Union
from uuid import UUID
import graphene
@@ -92,7 +93,7 @@ def _resolve_graphene_type(schema, type_name):
type_from_schema = schema.get_type(type_name)
if type_from_schema:
return type_from_schema.graphene_type
- raise GraphQLError("Could not resolve the type {}".format(type_name))
+ raise GraphQLError(f"Could not resolve the type {type_name}")
def get_nodes(
@@ -269,7 +270,7 @@ def query_fingerprint(document: GraphQLDocument) -> str:
def format_error(error, handled_exceptions):
- result: Dict[str, Any]
+ result: dict[str, Any]
if isinstance(error, GraphQLError):
result = format_graphql_error(error)
else:
diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.py
index e0e20ac16d..fce1bfa161 100644
--- a/saleor/graphql/utils/filters.py
+++ b/saleor/graphql/utils/filters.py
@@ -1,5 +1,5 @@
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List, Union
+from typing import TYPE_CHECKING, Union
from django.utils import timezone
@@ -86,7 +86,7 @@ def filter_where_range_field(qs, field, value):
def filter_where_by_string_field(
- qs: "QuerySet", field: str, value: Dict[str, Union[str, List[str]]]
+ qs: "QuerySet", field: str, value: dict[str, Union[str, list[str]]]
):
if value is None:
return qs.none()
@@ -99,7 +99,7 @@ def filter_where_by_string_field(
def filter_where_by_id_field(
- qs: "QuerySet", field: str, value: Dict[str, Union[str, List[str]]], type: str
+ qs: "QuerySet", field: str, value: dict[str, Union[str, list[str]]], type: str
):
from . import resolve_global_ids_to_primary_keys
@@ -117,7 +117,7 @@ def filter_where_by_id_field(
def filter_where_by_numeric_field(
qs: "QuerySet",
field: str,
- value: Dict[str, Union[Number, List[Number], Dict[str, Number]]],
+ value: dict[str, Union[Number, list[Number], dict[str, Number]]],
):
one_of = value.get("one_of")
range = value.get("range")
diff --git a/saleor/graphql/utils/sorting.py b/saleor/graphql/utils/sorting.py
index 48d776dc03..e13fcb6344 100644
--- a/saleor/graphql/utils/sorting.py
+++ b/saleor/graphql/utils/sorting.py
@@ -1,4 +1,4 @@
-from typing import Optional, Tuple
+from typing import Optional
from django.db.models import QuerySet
from graphql.error import GraphQLError
@@ -107,7 +107,7 @@ def get_model_default_ordering(model_class):
def sort_queryset_by_default(
queryset: QuerySet, reversed: bool
-) -> Tuple[QuerySet, dict]:
+) -> tuple[QuerySet, dict]:
"""Sort queryset by it's default ordering."""
queryset_model = queryset.model
default_ordering = ["pk"]
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 38095663e3..9c1e124b1e 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -2,7 +2,7 @@ import hashlib
import importlib
import json
from inspect import isclass
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any, Optional, Union
import opentracing
import opentracing.tags
@@ -72,7 +72,7 @@ class GraphQLView(View):
self,
schema=None,
executor=None,
- middleware: Optional[List[str]] = None,
+ middleware: Optional[list[str]] = None,
root_value=None,
backend=None,
):
@@ -200,7 +200,7 @@ class GraphQLView(View):
def get_response(
self, request: HttpRequest, data: dict
- ) -> Tuple[Optional[Dict[str, List[Any]]], int]:
+ ) -> tuple[Optional[dict[str, list[Any]]], int]:
with observability.report_gql_operation() as operation:
execution_result = self.execute_graphql_request(request, data)
status_code = 200
@@ -216,7 +216,7 @@ class GraphQLView(View):
response["data"] = execution_result.data
if execution_result.extensions:
response["extensions"] = execution_result.extensions
- result: Optional[Dict[str, List[Any]]] = response
+ result: Optional[dict[str, list[Any]]] = response
else:
result = None
operation.result = result
@@ -228,7 +228,7 @@ class GraphQLView(View):
def parse_query(
self, query: Optional[str]
- ) -> Tuple[Optional[GraphQLDocument], Optional[ExecutionResult]]:
+ ) -> tuple[Optional[GraphQLDocument], Optional[ExecutionResult]]:
"""Attempt to parse a query (mandatory) to a gql document object.
If no query was given or query is not a string, it returns an error.
@@ -308,7 +308,7 @@ class GraphQLView(View):
result = ExecutionResult(errors=cost_errors, invalid=True)
return set_query_cost_on_result(result, query_cost)
- extra_options: Dict[str, Optional[Any]] = {}
+ extra_options: dict[str, Optional[Any]] = {}
if self.executor:
# We only include it optionally since
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index e6e3889e19..2e6d94e20f 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -1,13 +1,9 @@
import sys
from collections import defaultdict
+from collections.abc import Iterable
from typing import (
TYPE_CHECKING,
- DefaultDict,
- Dict,
- Iterable,
- List,
Optional,
- Tuple,
TypedDict,
Union,
)
@@ -47,7 +43,7 @@ else:
CountryCode = Optional[str]
-VariantIdCountryCodeChannelSlug = Tuple[int, CountryCode, str]
+VariantIdCountryCodeChannelSlug = tuple[int, CountryCode, str]
class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
@@ -62,12 +58,12 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
context_key = "available_quantity_by_productvariant_and_country"
- def batch_load(self, keys: Iterable[VariantIdCountryCodeChannelSlug]) -> List[int]:
+ def batch_load(self, keys: Iterable[VariantIdCountryCodeChannelSlug]) -> list[int]:
# Split the list of keys by country first. A typical query will only touch
# a handful of unique countries but may access thousands of product variants,
# so it's cheaper to execute one query per country.
- variants_by_country_and_channel: DefaultDict[
- Tuple[CountryCode, str], List[int]
+ variants_by_country_and_channel: defaultdict[
+ tuple[CountryCode, str], list[int]
] = defaultdict(list)
for variant_id, country_code, channel_slug in keys:
variants_by_country_and_channel[(country_code, channel_slug)].append(
@@ -75,7 +71,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
)
# For each country code execute a single query for all product variants.
- quantity_by_variant_and_country: DefaultDict[
+ quantity_by_variant_and_country: defaultdict[
VariantIdCountryCodeChannelSlug, int
] = defaultdict(int)
@@ -100,7 +96,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
channel_slug: Optional[str],
variant_ids: Iterable[int],
site: Site,
- ) -> Iterable[Tuple[int, int]]:
+ ) -> Iterable[tuple[int, int]]:
# get stocks only for warehouses assigned to the shipping zones
# that are available in the given channel
stocks = (
@@ -277,12 +273,12 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
as a magic single-warehouse shipping zone.
"""
cc_warehouses_in_bulk = cc_warehouses.in_bulk()
- warehouse_ids_by_shipping_zone_by_variant: DefaultDict[
- int, DefaultDict[Union[int, UUID], List[UUID]]
+ warehouse_ids_by_shipping_zone_by_variant: defaultdict[
+ int, defaultdict[Union[int, UUID], list[UUID]]
] = defaultdict(lambda: defaultdict(list))
variants_with_global_cc_warehouses = []
- available_quantity_by_warehouse_id_and_variant_id: DefaultDict[
- UUID, Dict[int, int]
+ available_quantity_by_warehouse_id_and_variant_id: defaultdict[
+ UUID, dict[int, int]
] = defaultdict(lambda: defaultdict(int))
for stock in stocks:
reserved_quantity = stocks_reservations[stock.id]
@@ -340,7 +336,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
is the sum of the available quantities from all stocks that passed the country
or channel conditions.
"""
- quantity_map: DefaultDict[int, int] = defaultdict(int)
+ quantity_map: defaultdict[int, int] = defaultdict(int)
for (
variant_id,
warehouse_ids_shipping_zone,
@@ -392,8 +388,8 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
# Split the list of keys by country first. A typical query will only touch
# a handful of unique countries but may access thousands of product variants
# so it's cheaper to execute one query per country.
- variants_by_country_and_channel: DefaultDict[
- Tuple[CountryCode, str], List[int]
+ variants_by_country_and_channel: defaultdict[
+ tuple[CountryCode, str], list[int]
] = defaultdict(list)
for variant_id, country_code, channel_slug in keys:
variants_by_country_and_channel[(country_code, channel_slug)].append(
@@ -401,8 +397,8 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
)
# For each country code execute a single query for all product variants.
- stocks_by_variant_and_country: DefaultDict[
- VariantIdCountryCodeChannelSlug, List[Stock]
+ stocks_by_variant_and_country: defaultdict[
+ VariantIdCountryCodeChannelSlug, list[Stock]
] = defaultdict(list)
for key, variant_ids in variants_by_country_and_channel.items():
country_code, channel_slug = key
@@ -421,7 +417,7 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
country_code: Optional[CountryCode],
channel_slug: Optional[str],
variant_ids: Iterable[int],
- ) -> Iterable[Tuple[int, List[Stock]]]:
+ ) -> Iterable[tuple[int, list[Stock]]]:
# convert to set to not return the same stocks for the same variant twice
variant_ids_set = set(variant_ids)
stocks = (
@@ -451,7 +447,7 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
)
stocks = stocks.annotate_available_quantity().order_by("pk")
- stocks_by_variant_id_map: DefaultDict[int, List[Stock]] = defaultdict(list)
+ stocks_by_variant_id_map: defaultdict[int, list[Stock]] = defaultdict(list)
for stock in stocks:
stocks_by_variant_id_map[stock.product_variant_id].append(stock)
@@ -542,7 +538,7 @@ class PreorderQuantityReservedByVariantChannelListingIdLoader(DataLoader[int, in
.values("id", "quantity_reserved")
)
- reservations_by_listing_id: DefaultDict[int, int] = defaultdict(int)
+ reservations_by_listing_id: defaultdict[int, int] = defaultdict(int)
for listing in queryset:
reservations_by_listing_id[listing["id"]] += listing["quantity_reserved"]
return [reservations_by_listing_id[key] for key in keys]
@@ -551,7 +547,7 @@ class PreorderQuantityReservedByVariantChannelListingIdLoader(DataLoader[int, in
class WarehouseByIdLoader(DataLoader):
context_key = "warehouse_by_id"
- def batch_load(self, keys: Iterable[UUID]) -> List[Optional[Warehouse]]:
+ def batch_load(self, keys: Iterable[UUID]) -> list[Optional[Warehouse]]:
warehouses = (
Warehouse.objects.all().using(self.database_connection_name).in_bulk(keys)
)
diff --git a/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_assign.py b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_assign.py
index d9628f02a6..bbde11031c 100644
--- a/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_assign.py
+++ b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_assign.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import List
import graphene
from django.core.exceptions import ValidationError
@@ -36,7 +35,7 @@ class WarehouseShippingZoneAssign(ModelMutation, I18nMixin):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: List[str]
+ cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: list[str]
):
warehouse = cls.get_node_or_error(info, id, only_type=Warehouse)
shipping_zones = cls.get_nodes_or_error(
diff --git a/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_unassign.py b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_unassign.py
index 1ff53922f7..654da22170 100644
--- a/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_unassign.py
+++ b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_unassign.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from ....permission.enums import ProductPermissions
@@ -32,7 +30,7 @@ class WarehouseShippingZoneUnassign(ModelMutation, I18nMixin):
@classmethod
def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: List[str]
+ cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: list[str]
):
warehouse = cls.get_node_or_error(info, id, only_type=Warehouse)
shipping_zones = cls.get_nodes_or_error(
diff --git a/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py
index 0951f9df96..815092f89e 100644
--- a/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py
+++ b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py
@@ -77,10 +77,8 @@ def test_stocks_bulk_update_using_ids(
@patch(
- (
- "saleor.graphql.warehouse.bulk_mutations."
- "stock_bulk_update.get_webhooks_for_event"
- )
+ "saleor.graphql.warehouse.bulk_mutations."
+ "stock_bulk_update.get_webhooks_for_event"
)
@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")
def test_stocks_bulk_update_send_stock_updated_event(
diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.py
index 84bb7e3dd1..41ba000eb1 100644
--- a/saleor/graphql/webhook/subscription_payload.py
+++ b/saleor/graphql/webhook/subscription_payload.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, List, Optional
+from typing import Any, Optional
from celery.utils.log import get_task_logger
from django.conf import settings
@@ -63,7 +63,7 @@ def generate_payload_from_subscription(
subscription_query: Optional[str],
request: SaleorContext,
app: Optional[App] = None,
-) -> Optional[Dict[str, Any]]:
+) -> Optional[dict[str, Any]]:
"""Generate webhook payload from subscription query.
It uses a graphql's engine to build payload by using the same logic as response.
@@ -104,7 +104,7 @@ def generate_payload_from_subscription(
)
return None
- payload: List[Any] = []
+ payload: list[Any] = []
results.subscribe(payload.append)
if not payload:
diff --git a/saleor/graphql/webhook/subscription_query.py b/saleor/graphql/webhook/subscription_query.py
index 64323f8465..139ae3bba5 100644
--- a/saleor/graphql/webhook/subscription_query.py
+++ b/saleor/graphql/webhook/subscription_query.py
@@ -1,5 +1,5 @@
from enum import Flag
-from typing import Dict, List, Optional, Union
+from typing import Optional, Union
from django.core.exceptions import ValidationError
from graphene.utils.str_converters import to_snake_case
@@ -27,12 +27,12 @@ class SubscriptionQuery:
self.query: str = query
self.is_valid: bool = False
self.ast: Document = Document("")
- self.events: List[str] = []
+ self.events: list[str] = []
self.error_code: Optional[str] = None
self.errors = self.validate_query()
self.error_msg: str = ";".join(set([str(err.message) for err in self.errors]))
- def validate_query(self) -> List[Union[GraphQLSyntaxError, ValidationError]]:
+ def validate_query(self) -> list[Union[GraphQLSyntaxError, ValidationError]]:
from ..api import schema
graphql_backend = get_default_backend()
@@ -57,7 +57,7 @@ class SubscriptionQuery:
self.is_valid = True
return []
- def get_events_from_subscription(self) -> List[str]:
+ def get_events_from_subscription(self) -> list[str]:
subscription = self._get_subscription(self.ast)
if not subscription:
raise ValidationError(
@@ -72,12 +72,12 @@ class SubscriptionQuery:
code=WebhookErrorCode.UNABLE_TO_PARSE.value,
)
- events_and_fragments: Dict[str, IsFragment] = {}
+ events_and_fragments: dict[str, IsFragment] = {}
for event_type in event_types:
self._get_events_from_field(event_type, events_and_fragments)
fragment_definitions = self._get_fragment_definitions(self.ast)
- unpacked_events: Dict[str, IsFragment] = {}
+ unpacked_events: dict[str, IsFragment] = {}
for event_name, is_fragment in events_and_fragments.items():
if not is_fragment:
continue
@@ -107,7 +107,7 @@ class SubscriptionQuery:
@staticmethod
def _get_event_types_from_subscription(
subscription: OperationDefinition,
- ) -> List[Field]:
+ ) -> list[Field]:
return [
field
for field in subscription.selection_set.selections
@@ -117,8 +117,8 @@ class SubscriptionQuery:
@staticmethod
def _get_events_from_field(
field: Union[Field, FragmentDefinition],
- events: Dict[str, IsFragment],
- ) -> Dict[str, IsFragment]:
+ events: dict[str, IsFragment],
+ ) -> dict[str, IsFragment]:
if (
isinstance(field, FragmentDefinition)
and field.type_condition
@@ -138,8 +138,8 @@ class SubscriptionQuery:
return events
@staticmethod
- def _get_fragment_definitions(ast: Document) -> Dict[str, FragmentDefinition]:
- fragments: Dict[str, FragmentDefinition] = {}
+ def _get_fragment_definitions(ast: Document) -> dict[str, FragmentDefinition]:
+ fragments: dict[str, FragmentDefinition] = {}
for definition in ast.definitions:
if isinstance(definition, FragmentDefinition):
fragments[definition.name.value] = definition
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 70199dcd1a..aa74f60a76 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -2323,7 +2323,7 @@ class TranslationTypes(Union):
if instance_type in TRANSLATIONS_TYPES_MAP:
return TRANSLATIONS_TYPES_MAP[instance_type]
- return super(TranslationTypes, cls).resolve_type(instance, info)
+ return super().resolve_type(instance, info)
class TranslationBase(AbstractType):
diff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.py
index e1dc74cb76..8f2c3901f2 100644
--- a/saleor/graphql/webhook/types.py
+++ b/saleor/graphql/webhook/types.py
@@ -1,5 +1,3 @@
-from typing import List
-
import graphene
from ...core import models as core_models
@@ -208,7 +206,7 @@ class Webhook(ModelObjectType[models.Webhook]):
@staticmethod
def resolve_async_events(root: models.Webhook, info: ResolveInfo):
- def _filter_by_async_type(webhook_events: List[WebhookEvent]):
+ def _filter_by_async_type(webhook_events: list[WebhookEvent]):
return filter(
lambda webhook_event: webhook_event.event_type
in WebhookEventAsyncType.ALL,
@@ -223,7 +221,7 @@ class Webhook(ModelObjectType[models.Webhook]):
@staticmethod
def resolve_sync_events(root: models.Webhook, info: ResolveInfo):
- def _filter_by_sync_type(webhook_events: List[WebhookEvent]):
+ def _filter_by_sync_type(webhook_events: list[WebhookEvent]):
return filter(
lambda webhook_event: webhook_event.event_type
in WebhookEventSyncType.ALL,
diff --git a/saleor/menu/models.py b/saleor/menu/models.py
index 0f87c26f44..dc625032b4 100644
--- a/saleor/menu/models.py
+++ b/saleor/menu/models.py
@@ -72,12 +72,7 @@ class MenuItemTranslation(Translation):
def __repr__(self):
class_ = type(self)
- return "%s(pk=%r, name=%r, menu_item_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.menu_item_id,
- )
+ return f"{class_.__name__}(pk={self.id!r}, name={self.name!r}, menu_item_pk={self.menu_item_id!r})"
def __str__(self):
return self.name
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 0c3200cc31..0df69a4211 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1,8 +1,9 @@
import logging
from collections import defaultdict
+from collections.abc import Iterable
from copy import deepcopy
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, TypedDict
+from typing import TYPE_CHECKING, Optional, TypedDict
from uuid import UUID
from django.contrib.sites.models import Site
@@ -264,19 +265,19 @@ def order_returned(
order: "Order",
user: Optional[User],
app: Optional["App"],
- returned_lines: List[Tuple[QuantityType, OrderLine]],
+ returned_lines: list[tuple[QuantityType, OrderLine]],
):
order_returned_event(order=order, user=user, app=app, returned_lines=returned_lines)
update_order_status(order)
def order_fulfilled(
- fulfillments: List[Fulfillment],
+ fulfillments: list[Fulfillment],
user: Optional[User],
app: Optional["App"],
- fulfillment_lines: List[FulfillmentLine],
+ fulfillment_lines: list[FulfillmentLine],
manager: "PluginsManager",
- gift_card_lines_info: List[GiftCardLineData],
+ gift_card_lines_info: list[GiftCardLineData],
site_settings: "SiteSettings",
notify_customer=True,
):
@@ -315,12 +316,12 @@ def order_fulfilled(
def order_awaits_fulfillment_approval(
- fulfillments: List[Fulfillment],
+ fulfillments: list[Fulfillment],
user: Optional[User],
app: Optional["App"],
- fulfillment_lines: List[FulfillmentLine],
+ fulfillment_lines: list[FulfillmentLine],
manager: "PluginsManager",
- _gift_card_lines: List["GiftCardLineData"],
+ _gift_card_lines: list["GiftCardLineData"],
_site_settings: "SiteSettings",
_notify_customer=True,
):
@@ -776,13 +777,13 @@ def automatically_fulfill_digital_lines(
def _create_fulfillment_lines(
fulfillment: Fulfillment,
warehouse_pk: UUID,
- lines_data: List[OrderFulfillmentLineInfo],
+ lines_data: list[OrderFulfillmentLineInfo],
channel_slug: str,
- gift_card_lines_info: List[GiftCardLineData],
+ gift_card_lines_info: list[GiftCardLineData],
manager: "PluginsManager",
decrease_stock: bool = True,
allow_stock_to_be_exceeded: bool = False,
-) -> List[FulfillmentLine]:
+) -> list[FulfillmentLine]:
"""Modify stocks and allocations. Return list of unsaved FulfillmentLines.
Args:
@@ -821,7 +822,7 @@ def _create_fulfillment_lines(
.select_related("product_variant")
)
- variant_to_stock: Dict[int, List[Stock]] = defaultdict(list)
+ variant_to_stock: dict[int, list[Stock]] = defaultdict(list)
for stock in stocks:
variant_to_stock[stock.product_variant_id].append(stock)
@@ -894,14 +895,14 @@ def create_fulfillments(
user: Optional[User],
app: Optional["App"],
order: "Order",
- fulfillment_lines_for_warehouses: Dict[UUID, List[OrderFulfillmentLineInfo]],
+ fulfillment_lines_for_warehouses: dict[UUID, list[OrderFulfillmentLineInfo]],
manager: "PluginsManager",
site_settings: "SiteSettings",
notify_customer: bool = True,
approved: bool = True,
allow_stock_to_be_exceeded: bool = False,
tracking_number: str = "",
-) -> List[Fulfillment]:
+) -> list[Fulfillment]:
"""Fulfill order.
Function create fulfillments with lines.
@@ -941,9 +942,9 @@ def create_fulfillments(
InsufficientStock: If system hasn't containt enough item in stock for any line.
"""
- fulfillments: List[Fulfillment] = []
- fulfillment_lines: List[FulfillmentLine] = []
- gift_card_lines_info: List[GiftCardLineData] = []
+ fulfillments: list[Fulfillment] = []
+ fulfillment_lines: list[FulfillmentLine] = []
+ gift_card_lines_info: list[GiftCardLineData] = []
status = (
FulfillmentStatus.FULFILLED
if approved
@@ -992,7 +993,7 @@ def create_fulfillments(
def _get_fulfillment_line_if_exists(
- fulfillment_lines: List[FulfillmentLine], order_line_id, stock_id=None
+ fulfillment_lines: list[FulfillmentLine], order_line_id, stock_id=None
):
for line in fulfillment_lines:
if line.order_line_id == order_line_id and line.stock_id == stock_id:
@@ -1002,10 +1003,10 @@ def _get_fulfillment_line_if_exists(
def _get_fulfillment_line(
target_fulfillment: Fulfillment,
- lines_in_target_fulfillment: List[FulfillmentLine],
+ lines_in_target_fulfillment: list[FulfillmentLine],
order_line_id: OrderLineIDType,
stock_id: Optional[int] = None,
-) -> Tuple[FulfillmentLine, bool]:
+) -> tuple[FulfillmentLine, bool]:
"""Get fulfillment line if extists or create new fulfillment line object."""
# Check if line for order_line_id and stock_id does not exist in DB.
moved_line = _get_fulfillment_line_if_exists(
@@ -1028,15 +1029,15 @@ def _get_fulfillment_line(
def _move_order_lines_to_target_fulfillment(
- order_lines_to_move: List[OrderLineInfo],
+ order_lines_to_move: list[OrderLineInfo],
target_fulfillment: Fulfillment,
manager: "PluginsManager",
-) -> List[FulfillmentLine]:
+) -> list[FulfillmentLine]:
"""Move order lines with given quantity to the target fulfillment."""
- fulfillment_lines_to_create: List[FulfillmentLine] = []
- order_lines_to_update: List[OrderLine] = []
+ fulfillment_lines_to_create: list[FulfillmentLine] = []
+ order_lines_to_update: list[OrderLine] = []
- lines_to_dellocate: List[OrderLineInfo] = []
+ lines_to_dellocate: list[OrderLineInfo] = []
# transaction ensures consistent data in order lines and fulfillment lines
with traced_atomic_transaction():
for line_data in order_lines_to_move:
@@ -1084,14 +1085,14 @@ def _move_order_lines_to_target_fulfillment(
def _move_fulfillment_lines_to_target_fulfillment(
- fulfillment_lines_to_move: List[FulfillmentLineData],
- lines_in_target_fulfillment: List[FulfillmentLine],
+ fulfillment_lines_to_move: list[FulfillmentLineData],
+ lines_in_target_fulfillment: list[FulfillmentLine],
target_fulfillment: Fulfillment,
):
"""Move fulfillment lines with given quantity to the target fulfillment."""
- fulfillment_lines_to_create: List[FulfillmentLine] = []
- fulfillment_lines_to_update: List[FulfillmentLine] = []
- empty_fulfillment_lines_to_delete: List[FulfillmentLine] = []
+ fulfillment_lines_to_create: list[FulfillmentLine] = []
+ fulfillment_lines_to_update: list[FulfillmentLine] = []
+ empty_fulfillment_lines_to_delete: list[FulfillmentLine] = []
# transaction ensures consistency in fulfillment lines data
with traced_atomic_transaction():
@@ -1155,8 +1156,8 @@ def create_refund_fulfillment(
app: Optional["App"],
order,
payment,
- order_lines_to_refund: List[OrderLineInfo],
- fulfillment_lines_to_refund: List[FulfillmentLineData],
+ order_lines_to_refund: list[OrderLineInfo],
+ fulfillment_lines_to_refund: list[FulfillmentLineData],
manager: "PluginsManager",
amount=None,
refund_shipping_costs=False,
@@ -1249,13 +1250,13 @@ def create_replace_order(
user: Optional[User],
app: Optional["App"],
original_order: "Order",
- order_lines_to_replace: List[OrderLineInfo],
- fulfillment_lines_to_replace: List[FulfillmentLineData],
+ order_lines_to_replace: list[OrderLineInfo],
+ fulfillment_lines_to_replace: list[FulfillmentLineData],
) -> "Order":
"""Create draft order with lines to replace."""
replace_order = _populate_replace_order_fields(original_order)
- order_line_to_create: Dict[OrderLineIDType, OrderLine] = dict()
+ order_line_to_create: dict[OrderLineIDType, OrderLine] = dict()
# transaction is needed to ensure data consistency for order lines
with traced_atomic_transaction():
# iterate over lines without fulfillment to get the items for replace.
@@ -1312,8 +1313,8 @@ def create_replace_order(
def _move_lines_to_return_fulfillment(
- order_lines: List[OrderLineInfo],
- fulfillment_lines: List[FulfillmentLineData],
+ order_lines: list[OrderLineInfo],
+ fulfillment_lines: list[FulfillmentLineData],
fulfillment_status: str,
order: "Order",
total_refund_amount: Optional[Decimal],
@@ -1371,8 +1372,8 @@ def _move_lines_to_return_fulfillment(
def _move_lines_to_replace_fulfillment(
- order_lines_to_replace: List[OrderLineInfo],
- fulfillment_lines_to_replace: List[FulfillmentLineData],
+ order_lines_to_replace: list[OrderLineInfo],
+ fulfillment_lines_to_replace: list[FulfillmentLineData],
order: "Order",
manager: "PluginsManager",
) -> Fulfillment:
@@ -1396,8 +1397,8 @@ def create_return_fulfillment(
user: Optional[User],
app: Optional["App"],
order: "Order",
- order_lines: List[OrderLineInfo],
- fulfillment_lines: List[FulfillmentLineData],
+ order_lines: list[OrderLineInfo],
+ fulfillment_lines: list[FulfillmentLineData],
total_refund_amount: Optional[Decimal],
shipping_refund_amount: Optional[Decimal],
manager: "PluginsManager",
@@ -1415,7 +1416,7 @@ def create_return_fulfillment(
shipping_refund_amount=shipping_refund_amount,
manager=manager,
)
- returned_lines: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
+ returned_lines: dict[OrderLineIDType, tuple[QuantityType, OrderLine]] = dict()
order_lines_with_fulfillment = OrderLine.objects.in_bulk(
[line_data.line.order_line_id for line_data in fulfillment_lines]
)
@@ -1450,10 +1451,10 @@ def process_replace(
user: Optional[User],
app: Optional["App"],
order: "Order",
- order_lines: List[OrderLineInfo],
- fulfillment_lines: List[FulfillmentLineData],
+ order_lines: list[OrderLineInfo],
+ fulfillment_lines: list[FulfillmentLineData],
manager: "PluginsManager",
-) -> Tuple[Fulfillment, Optional["Order"]]:
+) -> tuple[Fulfillment, Optional["Order"]]:
"""Create replace fulfillment and new draft order.
Move all requested lines to fulfillment with status replaced. Based on original
@@ -1495,13 +1496,13 @@ def create_fulfillments_for_returned_products(
app: Optional["App"],
order: "Order",
payment: Optional[Payment],
- order_lines: List[OrderLineInfo],
- fulfillment_lines: List[FulfillmentLineData],
+ order_lines: list[OrderLineInfo],
+ fulfillment_lines: list[FulfillmentLineData],
manager: "PluginsManager",
refund: bool = False,
amount: Optional[Decimal] = None,
refund_shipping_costs=False,
-) -> Tuple[Fulfillment, Optional[Fulfillment], Optional[Order]]:
+) -> tuple[Fulfillment, Optional[Fulfillment], Optional[Order]]:
"""Process the request for replacing or returning the products.
Process the refund when the refund is set to True. The amount of refund will be
@@ -1581,9 +1582,9 @@ def create_fulfillments_for_returned_products(
def _calculate_refund_amount(
- return_order_lines: List[OrderLineInfo],
- return_fulfillment_lines: List[FulfillmentLineData],
- lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]],
+ return_order_lines: list[OrderLineInfo],
+ return_fulfillment_lines: list[FulfillmentLineData],
+ lines_to_refund: dict[OrderLineIDType, tuple[QuantityType, OrderLine]],
) -> Decimal:
refund_amount = Decimal(0)
for line_data in return_order_lines:
@@ -1619,13 +1620,13 @@ def _process_refund(
app: Optional["App"],
order: "Order",
payment: Optional[Payment],
- order_lines_to_refund: List[OrderLineInfo],
- fulfillment_lines_to_refund: List[FulfillmentLineData],
+ order_lines_to_refund: list[OrderLineInfo],
+ fulfillment_lines_to_refund: list[FulfillmentLineData],
amount: Optional[Decimal],
refund_shipping_costs: bool,
manager: "PluginsManager",
):
- lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
+ lines_to_refund: dict[OrderLineIDType, tuple[QuantityType, OrderLine]] = dict()
refund_data = RefundData(
order_lines_to_refund=order_lines_to_refund,
fulfillment_lines_to_refund=fulfillment_lines_to_refund,
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index c15d276cab..321f43bcc0 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -1,4 +1,5 @@
-from typing import TYPE_CHECKING, Iterable
+from collections.abc import Iterable
+from typing import TYPE_CHECKING
from prices import Money, TaxedMoney
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index b01b7bb4b4..54beda4944 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import Iterable, Optional, Tuple, cast
+from typing import Optional, cast
from django.db import transaction
from django.db.models import prefetch_related_objects
@@ -182,7 +183,7 @@ def fetch_order_prices_if_expired(
manager: PluginsManager,
lines: Optional[Iterable[OrderLine]] = None,
force_update: bool = False,
-) -> Tuple[Order, Optional[Iterable[OrderLine]]]:
+) -> tuple[Order, Optional[Iterable[OrderLine]]]:
"""Fetch order prices with taxes.
First calculate and apply all order prices with taxes separately,
diff --git a/saleor/order/events.py b/saleor/order/events.py
index cb3e49afa2..f9c1828ac6 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -1,5 +1,5 @@
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Optional, Union
from ..account import events as account_events
from ..account.models import User
@@ -24,7 +24,7 @@ def _lines_per_quantity_to_line_object_list(order_lines):
]
-def _get_payment_data(amount: Optional[Decimal], payment: Payment) -> Dict:
+def _get_payment_data(amount: Optional[Decimal], payment: Payment) -> dict:
return {
"parameters": {
"amount": amount,
@@ -262,7 +262,7 @@ def order_added_products_event(
order: Order,
user: Optional[User],
app: Optional[App],
- order_lines: List[OrderLine],
+ order_lines: list[OrderLine],
quantity_diff: Optional[int] = None,
) -> OrderEvent:
if quantity_diff:
@@ -284,7 +284,7 @@ def order_removed_products_event(
order: Order,
user: Optional[User],
app: Optional[App],
- order_lines: List[OrderLine],
+ order_lines: list[OrderLine],
quantity_diff: Optional[int] = None,
) -> OrderEvent:
if quantity_diff:
@@ -307,7 +307,7 @@ def draft_order_created_from_replace_event(
original_order: Order,
user: Optional[User],
app: Optional[App],
- lines: List[OrderLine],
+ lines: list[OrderLine],
):
parameters = {
"related_order_pk": original_order.pk,
@@ -576,7 +576,7 @@ def fulfillment_fulfilled_items_event(
order: Order,
user: Optional[User],
app: Optional[App],
- fulfillment_lines: List[FulfillmentLine],
+ fulfillment_lines: list[FulfillmentLine],
) -> OrderEvent:
return OrderEvent.objects.create(
order=order,
@@ -592,7 +592,7 @@ def fulfillment_awaits_approval_event(
order: Order,
user: Optional[User],
app: Optional[App],
- fulfillment_lines: List[FulfillmentLine],
+ fulfillment_lines: list[FulfillmentLine],
) -> OrderEvent:
return OrderEvent.objects.create(
order=order,
@@ -608,7 +608,7 @@ def order_returned_event(
order: Order,
user: Optional[User],
app: Optional[App],
- returned_lines: List[Tuple[int, OrderLine]],
+ returned_lines: list[tuple[int, OrderLine]],
):
return OrderEvent.objects.create(
order=order,
@@ -629,7 +629,7 @@ def fulfillment_replaced_event(
order: Order,
user: Optional[User],
app: Optional[App],
- replaced_lines: List[OrderLine],
+ replaced_lines: list[OrderLine],
):
return OrderEvent.objects.create(
order=order,
@@ -645,7 +645,7 @@ def fulfillment_refunded_event(
order: Order,
user: Optional[User],
app: Optional[App],
- refunded_lines: List[Tuple[int, OrderLine]],
+ refunded_lines: list[tuple[int, OrderLine]],
amount: Decimal,
shipping_costs_included: bool,
):
@@ -688,7 +688,7 @@ def fulfillment_tracking_updated_event(
def order_note_added_event(
*, order: Order, user: Optional[User], app: Optional[App], message: str
) -> OrderEvent:
- kwargs: Dict[str, Union[Optional[App], Optional[User]]] = {"app": app}
+ kwargs: dict[str, Union[Optional[App], Optional[User]]] = {"app": app}
if user is not None:
if order.user is not None and order.user.pk == user.pk:
account_events.customer_added_to_note_order_event(
@@ -761,7 +761,7 @@ def order_discount_event(
def order_discounts_automatically_updated_event(
- order: Order, changed_order_discounts: List[Tuple["OrderDiscount", "OrderDiscount"]]
+ order: Order, changed_order_discounts: list[tuple["OrderDiscount", "OrderDiscount"]]
):
for previous_order_discount, current_order_discount in changed_order_discounts:
order_discount_automatically_updated_event(
@@ -901,7 +901,7 @@ def order_line_product_removed_event(
order: Order,
user: Optional[User],
app: Optional[App],
- order_lines: List[Tuple[int, OrderLine]],
+ order_lines: list[tuple[int, OrderLine]],
):
return OrderEvent.objects.create(
type=OrderEvents.ORDER_LINE_PRODUCT_DELETED,
@@ -916,7 +916,7 @@ def order_line_variant_removed_event(
order: Order,
user: Optional[User],
app: Optional[App],
- order_lines: List[Tuple[int, OrderLine]],
+ order_lines: list[tuple[int, OrderLine]],
):
return OrderEvent.objects.create(
type=OrderEvents.ORDER_LINE_VARIANT_DELETED,
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index 930365af31..9d1b364e4a 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Iterable, List, Optional
+from typing import TYPE_CHECKING, Optional
from uuid import UUID
if TYPE_CHECKING:
@@ -43,7 +44,7 @@ def fetch_order_info(order: "Order") -> OrderInfo:
return order_data
-def fetch_order_lines(order: "Order") -> List[OrderLineInfo]:
+def fetch_order_lines(order: "Order") -> list[OrderLineInfo]:
lines = order.lines.prefetch_related("variant__digital_content")
lines_info = []
for line in lines:
diff --git a/saleor/order/migrations/0001_initial.py b/saleor/order/migrations/0001_initial.py
index d5a9a4dab7..18ff21dbe8 100644
--- a/saleor/order/migrations/0001_initial.py
+++ b/saleor/order/migrations/0001_initial.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
diff --git a/saleor/order/migrations/0002_auto_20150820_1955.py b/saleor/order/migrations/0002_auto_20150820_1955.py
index ce13ffd142..5c09dc74e4 100644
--- a/saleor/order/migrations/0002_auto_20150820_1955.py
+++ b/saleor/order/migrations/0002_auto_20150820_1955.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations
diff --git a/saleor/order/migrations/0003_auto_20150825_1433.py b/saleor/order/migrations/0003_auto_20150825_1433.py
index 8a318d0056..859940e185 100644
--- a/saleor/order/migrations/0003_auto_20150825_1433.py
+++ b/saleor/order/migrations/0003_auto_20150825_1433.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/order/migrations/0004_order_total.py b/saleor/order/migrations/0004_order_total.py
index 759b5adc41..b451dd696b 100644
--- a/saleor/order/migrations/0004_order_total.py
+++ b/saleor/order/migrations/0004_order_total.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/order/migrations/0005_deliverygroup_last_updated.py b/saleor/order/migrations/0005_deliverygroup_last_updated.py
index f52f7cd1e1..d206665d98 100644
--- a/saleor/order/migrations/0005_deliverygroup_last_updated.py
+++ b/saleor/order/migrations/0005_deliverygroup_last_updated.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/order/migrations/0006_deliverygroup_shipping_method.py b/saleor/order/migrations/0006_deliverygroup_shipping_method.py
index 8145e0131c..0f1a66a889 100644
--- a/saleor/order/migrations/0006_deliverygroup_shipping_method.py
+++ b/saleor/order/migrations/0006_deliverygroup_shipping_method.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/order/migrations/0007_deliverygroup_tracking_number.py b/saleor/order/migrations/0007_deliverygroup_tracking_number.py
index 3529a43019..f5a0a58816 100644
--- a/saleor/order/migrations/0007_deliverygroup_tracking_number.py
+++ b/saleor/order/migrations/0007_deliverygroup_tracking_number.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/order/migrations/0008_auto_20151026_0820.py b/saleor/order/migrations/0008_auto_20151026_0820.py
index c0c6b0d913..72ed24c145 100644
--- a/saleor/order/migrations/0008_auto_20151026_0820.py
+++ b/saleor/order/migrations/0008_auto_20151026_0820.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/order/migrations/0009_auto_20151201_0820.py b/saleor/order/migrations/0009_auto_20151201_0820.py
index 62ee608a74..20bf1b5a0a 100644
--- a/saleor/order/migrations/0009_auto_20151201_0820.py
+++ b/saleor/order/migrations/0009_auto_20151201_0820.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/order/migrations/0010_auto_20160119_0541.py b/saleor/order/migrations/0010_auto_20160119_0541.py
index 266e202471..15a2229772 100644
--- a/saleor/order/migrations/0010_auto_20160119_0541.py
+++ b/saleor/order/migrations/0010_auto_20160119_0541.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-01-19 11:41
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/order/migrations/0011_auto_20160207_0534.py b/saleor/order/migrations/0011_auto_20160207_0534.py
index 017aadc1cc..9d9bb8b23b 100644
--- a/saleor/order/migrations/0011_auto_20160207_0534.py
+++ b/saleor/order/migrations/0011_auto_20160207_0534.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-02-07 11:34
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/order/migrations/0012_auto_20160216_1032.py b/saleor/order/migrations/0012_auto_20160216_1032.py
index 0a9de95352..14ecde077a 100644
--- a/saleor/order/migrations/0012_auto_20160216_1032.py
+++ b/saleor/order/migrations/0012_auto_20160216_1032.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-02-16 16:32
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/order/migrations/0013_auto_20160906_0741.py b/saleor/order/migrations/0013_auto_20160906_0741.py
index 363620c207..c6947f34ee 100644
--- a/saleor/order/migrations/0013_auto_20160906_0741.py
+++ b/saleor/order/migrations/0013_auto_20160906_0741.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.1 on 2016-09-06 12:41
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/order/migrations/0014_auto_20161028_0955.py b/saleor/order/migrations/0014_auto_20161028_0955.py
index 3b4dac6e2d..4feb8ee93c 100644
--- a/saleor/order/migrations/0014_auto_20161028_0955.py
+++ b/saleor/order/migrations/0014_auto_20161028_0955.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.1 on 2016-10-28 14:55
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/order/migrations/0015_auto_20170206_0407.py b/saleor/order/migrations/0015_auto_20170206_0407.py
index 6c55d3ae98..b068b57a19 100644
--- a/saleor/order/migrations/0015_auto_20170206_0407.py
+++ b/saleor/order/migrations/0015_auto_20170206_0407.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-06 10:07
-from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
diff --git a/saleor/order/migrations/0016_order_language_code.py b/saleor/order/migrations/0016_order_language_code.py
index 982cd855c3..b5efd35e47 100644
--- a/saleor/order/migrations/0016_order_language_code.py
+++ b/saleor/order/migrations/0016_order_language_code.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-14 16:24
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/order/migrations/0017_auto_20170906_0556.py b/saleor/order/migrations/0017_auto_20170906_0556.py
index a10447af3b..8d76485690 100644
--- a/saleor/order/migrations/0017_auto_20170906_0556.py
+++ b/saleor/order/migrations/0017_auto_20170906_0556.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-06 10:56
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/order/migrations/0018_auto_20170919_0839.py b/saleor/order/migrations/0018_auto_20170919_0839.py
index 0de737097c..7878146cda 100644
--- a/saleor/order/migrations/0018_auto_20170919_0839.py
+++ b/saleor/order/migrations/0018_auto_20170919_0839.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-19 13:39
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/order/migrations/0019_auto_20171109_1423.py b/saleor/order/migrations/0019_auto_20171109_1423.py
index e86c86a7d8..c338c5ad8f 100644
--- a/saleor/order/migrations/0019_auto_20171109_1423.py
+++ b/saleor/order/migrations/0019_auto_20171109_1423.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-09 20:23
-from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
diff --git a/saleor/order/migrations/0020_auto_20171123_0609.py b/saleor/order/migrations/0020_auto_20171123_0609.py
index 650099ca53..dd44d62f8b 100644
--- a/saleor/order/migrations/0020_auto_20171123_0609.py
+++ b/saleor/order/migrations/0020_auto_20171123_0609.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-23 12:09
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/order/migrations/0021_auto_20171129_1004.py b/saleor/order/migrations/0021_auto_20171129_1004.py
index bd77c044a2..4971820a36 100644
--- a/saleor/order/migrations/0021_auto_20171129_1004.py
+++ b/saleor/order/migrations/0021_auto_20171129_1004.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-29 16:04
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/order/migrations/0022_auto_20171205_0428.py b/saleor/order/migrations/0022_auto_20171205_0428.py
index a43e06a643..416485efd9 100644
--- a/saleor/order/migrations/0022_auto_20171205_0428.py
+++ b/saleor/order/migrations/0022_auto_20171205_0428.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-12-05 10:28
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/order/migrations/0023_auto_20171206_0506.py b/saleor/order/migrations/0023_auto_20171206_0506.py
index 90564fdf99..5aed1ee052 100644
--- a/saleor/order/migrations/0023_auto_20171206_0506.py
+++ b/saleor/order/migrations/0023_auto_20171206_0506.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-12-06 11:06
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/order/migrations/0031_auto_20180119_0405.py b/saleor/order/migrations/0031_auto_20180119_0405.py
index f932e14480..162ed4932e 100644
--- a/saleor/order/migrations/0031_auto_20180119_0405.py
+++ b/saleor/order/migrations/0031_auto_20180119_0405.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-19 10:05
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/order/migrations/0070_drop_update_event_and_rename_events.py b/saleor/order/migrations/0070_drop_update_event_and_rename_events.py
index b4e33cbd37..732393639e 100644
--- a/saleor/order/migrations/0070_drop_update_event_and_rename_events.py
+++ b/saleor/order/migrations/0070_drop_update_event_and_rename_events.py
@@ -44,9 +44,7 @@ def _move_updated_events_to_other(apps, *_args, **_kwargs):
for event in cls.objects.filter(type="updated").all():
event.type = OrderEvents.OTHER
- event.parameters["message"] = "Order details were updated by %(user_name)s" % {
- "user_name": event.user
- }
+ event.parameters["message"] = f"Order details were updated by {event.user}"
event.save(update_fields=["type", "parameters"])
diff --git a/saleor/order/models.py b/saleor/order/models.py
index c0f384d2ba..6714792954 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -1,7 +1,7 @@
from decimal import Decimal
from operator import attrgetter
from re import match
-from typing import TYPE_CHECKING, List, Optional, cast
+from typing import TYPE_CHECKING, Optional, cast
from uuid import uuid4
from django.conf import settings
@@ -363,16 +363,16 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
return self.user_email
def __repr__(self):
- return "<Order #%r>" % (self.id,)
+ return f"<Order #{self.id!r}>"
def __str__(self):
- return "#%d" % (self.id,)
+ return f"#{self.id}"
def get_last_payment(self) -> Optional[Payment]:
# Skipping a partial payment is a temporary workaround for storing a basic data
# about partial payment from Adyen plugin. This is something that will removed
# in 3.1 by introducing a partial payments feature.
- payments: List[Payment] = [
+ payments: list[Payment] = [
payment for payment in self.payments.all() if not payment.partial
]
return max(payments, default=None, key=attrgetter("pk"))
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index 414825c667..647e916f15 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, List, Optional
+from typing import TYPE_CHECKING, Optional
from urllib.parse import urlencode
from django.forms import model_to_dict
@@ -34,7 +35,7 @@ def get_image_payload(instance: ProductMedia):
}
-def get_default_images_payload(images: List[ProductMedia]):
+def get_default_images_payload(images: list[ProductMedia]):
first_image_payload = None
first_image = images[0] if images else None
if first_image:
diff --git a/saleor/order/search.py b/saleor/order/search.py
index 391ef64551..35a0873078 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
import graphene
from django.conf import settings
@@ -24,7 +24,7 @@ def update_order_search_vector(order: "Order", *, save: bool = True):
def prepare_order_search_vector_value(
order: "Order", *, already_prefetched=False
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
if not already_prefetched:
prefetch_related_objects(
[order],
@@ -82,7 +82,7 @@ def prepare_order_search_vector_value(
def generate_order_transactions_search_vector_value(
order: "Order",
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
transaction_vectors = []
for transaction in order.payment_transactions.all()[
: settings.SEARCH_ORDERS_MAX_INDEXED_TRANSACTIONS
@@ -118,7 +118,7 @@ def generate_order_transactions_search_vector_value(
def generate_order_payments_search_vector_value(
order: "Order",
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
payment_vectors = []
for payment in order.payments.all()[: settings.SEARCH_ORDERS_MAX_INDEXED_PAYMENTS]:
payment_vectors.append(
@@ -141,7 +141,7 @@ def generate_order_payments_search_vector_value(
def generate_order_discounts_search_vector_value(
order: "Order",
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
discount_vectors = []
for discount in order.discounts.all()[
: settings.SEARCH_ORDERS_MAX_INDEXED_DISCOUNTS
@@ -167,7 +167,7 @@ def generate_order_discounts_search_vector_value(
def generate_order_lines_search_vector_value(
order: "Order",
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
line_vectors = []
for line in order.lines.all()[: settings.SEARCH_ORDERS_MAX_INDEXED_LINES]:
if line.product_sku:
diff --git a/saleor/order/tasks.py b/saleor/order/tasks.py
index 1651cc7b94..75c8c61218 100644
--- a/saleor/order/tasks.py
+++ b/saleor/order/tasks.py
@@ -1,6 +1,5 @@
import logging
from datetime import timedelta
-from typing import List
from django.db.models import Exists, F, Func, OuterRef, Subquery, Value
from django.utils import timezone
@@ -28,7 +27,7 @@ DELETE_EXPIRED_ORDER_BATCH_SIZE = 5000
@app.task
-def recalculate_orders_task(order_ids: List[int]):
+def recalculate_orders_task(order_ids: list[int]):
orders = Order.objects.filter(id__in=order_ids)
for order in orders:
diff --git a/saleor/order/tests/test_tasks.py b/saleor/order/tests/test_tasks.py
index 92ff5d0c8b..e53d90e4ca 100644
--- a/saleor/order/tests/test_tasks.py
+++ b/saleor/order/tests/test_tasks.py
@@ -1,10 +1,10 @@
from datetime import timedelta
+from unittest import mock
+from unittest.mock import patch
-import mock
import pytest
from django.utils import timezone
from freezegun import freeze_time
-from mock import patch
from ...discount.models import VoucherCustomer
from ...warehouse.models import Allocation
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 586dff7716..e03d46ad02 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,6 +1,7 @@
+from collections.abc import Iterable
from decimal import Decimal
from functools import wraps
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, cast
+from typing import TYPE_CHECKING, Optional, cast
from django.db.models import QuerySet, Sum
from django.utils import timezone
@@ -330,7 +331,7 @@ def create_order_line(
def create_order_line_discounts(
line: "OrderLine", rules_info: Iterable["VariantPromotionRuleInfo"]
) -> Iterable["OrderLineDiscount"]:
- line_discounts_to_create: List[OrderLineDiscount] = []
+ line_discounts_to_create: list[OrderLineDiscount] = []
for rule_info in rules_info:
rule = rule_info.rule
rule_discount_amount = rule_info.variant_listing_promotion_rule.discount_amount
@@ -417,7 +418,7 @@ def add_gift_cards_to_order(
):
order_gift_cards = []
gift_cards_to_update = []
- balance_data: List[Tuple[GiftCard, float]] = []
+ balance_data: list[tuple[GiftCard, float]] = []
used_by_user = checkout_info.user
used_by_email = cast(str, checkout_info.get_customer_email())
for gift_card in checkout_info.checkout.gift_cards.select_for_update():
@@ -447,7 +448,7 @@ def add_gift_cards_to_order(
def update_gift_card_balance(
gift_card: GiftCard,
total_price_left: Money,
- balance_data: List[Tuple[GiftCard, float]],
+ balance_data: list[tuple[GiftCard, float]],
) -> Money:
previous_balance = gift_card.current_balance
if total_price_left < gift_card.current_balance:
@@ -602,7 +603,7 @@ def sum_order_totals(qs, currency_code):
def get_all_shipping_methods_for_order(
order: Order,
shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
-) -> List[ShippingMethodData]:
+) -> list[ShippingMethodData]:
if not order.is_shipping_required():
return []
@@ -634,7 +635,7 @@ def get_valid_shipping_methods_for_order(
order: Order,
shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
manager: "PluginsManager",
-) -> List[ShippingMethodData]:
+) -> list[ShippingMethodData]:
"""Return a list of shipping methods according to Saleor's own business logic."""
valid_methods = get_all_shipping_methods_for_order(order, shipping_channel_listings)
if not valid_methods:
@@ -689,7 +690,7 @@ def get_discounted_lines(lines, voucher):
def get_prices_of_discounted_specific_product(
lines: Iterable[OrderLine],
voucher: Voucher,
-) -> List[Money]:
+) -> list[Money]:
"""Get prices of variants belonging to the discounted specific products.
Specific products are products, collections and categories.
@@ -767,7 +768,7 @@ def get_total_order_discount_excluding_shipping(order: Order) -> Money:
return total_order_discount
-def get_order_discounts(order: Order) -> List[OrderDiscount]:
+def get_order_discounts(order: Order) -> list[OrderDiscount]:
"""Return all discounts applied to the order by staff user."""
return list(order.discounts.filter(type=DiscountType.MANUAL))
diff --git a/saleor/page/models.py b/saleor/page/models.py
index 7fb0ece705..affbf35bc3 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -57,12 +57,7 @@ class PageTranslation(SeoModelTranslation):
def __repr__(self):
class_ = type(self)
- return "%s(pk=%r, title=%r, page_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.title,
- self.page_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, title={self.title!r}, page_pk={self.page_id!r})"
def __str__(self):
return self.title if self.title else str(self.pk)
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 84bdd1f740..d40b11d34f 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -3,7 +3,7 @@ from enum import Enum
class PaymentError(Exception):
def __init__(self, message, code=None):
- super(PaymentError, self).__init__(message, code)
+ super().__init__(message, code)
self.message = message
self.code = code
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 475c8eb4d4..dec610e66c 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Callable, List, Optional
+from typing import TYPE_CHECKING, Callable, Optional
from ..account.models import User
from ..app.models import App
@@ -479,13 +479,13 @@ def list_payment_sources(
customer_id: str,
manager: "PluginsManager",
channel_slug: str,
-) -> List["CustomerSource"]:
+) -> list["CustomerSource"]:
return manager.list_payment_sources(gateway, customer_id, channel_slug=channel_slug)
def list_gateways(
manager: "PluginsManager", channel_slug: Optional[str] = None
-) -> List["PaymentGateway"]:
+) -> list["PaymentGateway"]:
return manager.list_payment_gateways(channel_slug=channel_slug)
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 0f14fe5825..3e75d4fc5d 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -1,5 +1,6 @@
import json
-from typing import Iterable, List, Optional
+from collections.abc import Iterable
+from typing import Optional
from urllib.parse import urlencode, urljoin
import opentracing
@@ -304,7 +305,7 @@ class AdyenGatewayPlugin(BasePlugin):
checkout_info: Optional["CheckoutInfo"],
checkout_lines: Optional[Iterable["CheckoutLineInfo"]],
previous_value,
- ) -> List["PaymentGateway"]:
+ ) -> list["PaymentGateway"]:
"""Fetch current configuration for given checkout.
It calls an Adyen API to fetch all available payment methods for given checkout.
@@ -485,7 +486,7 @@ class AdyenGatewayPlugin(BasePlugin):
@classmethod
def _update_config_items(
- cls, configuration_to_update: List[dict], current_config: List[dict]
+ cls, configuration_to_update: list[dict], current_config: list[dict]
):
for item in configuration_to_update:
if item.get("name") == "notification-password" and item["value"]:
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index 6c2bf84550..9b8c30fb09 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -1,7 +1,8 @@
import json
import logging
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Optional
+from typing import TYPE_CHECKING, Any, Callable, Optional
import Adyen
import opentracing
@@ -81,7 +82,7 @@ def get_tax_percentage_in_adyen_format(total_gross, total_net):
def api_call(
- request_data: Optional[Dict[str, Any]], method: Callable, **kwargs
+ request_data: Optional[dict[str, Any]], method: Callable, **kwargs
) -> Adyen.Adyen:
try:
return method(request_data, **kwargs)
@@ -139,7 +140,7 @@ def request_data_for_payment(
return_url: str,
merchant_account: str,
native_3d_secure: bool,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
payment_data = payment_information.data or {}
if not payment_data.pop("is_valid", True):
@@ -339,7 +340,7 @@ def request_data_for_gateway_config(
checkout_info: "CheckoutInfo",
lines: Optional[Iterable[CheckoutLineInfo]],
merchant_account,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
manager = get_plugins_manager()
checkout = checkout_info.checkout
address = checkout_info.shipping_address or checkout_info.billing_address
@@ -374,7 +375,7 @@ def request_for_payment_refund(
graphql_payment_id: str,
merchant_account: str,
token: str,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
return {
"merchantAccount": merchant_account,
"modificationAmount": {
@@ -388,7 +389,7 @@ def request_for_payment_refund(
def request_for_payment_capture(
payment_information: "PaymentData", merchant_account: str, token: str
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
return {
"merchantAccount": merchant_account,
"modificationAmount": {
@@ -499,7 +500,7 @@ def get_request_data_for_check_payment(data: dict, merchant_account: str) -> dic
amount_input = data["card"].get("money")
security_code = data["card"].get("cvc")
- request_data: Dict[str, Any] = {
+ request_data: dict[str, Any] = {
"merchantAccount": merchant_account,
"paymentMethod": {
"type": data["method"],
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 752fba77be..549dcbaee2 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -4,9 +4,10 @@ import hashlib
import hmac
import json
import logging
+from collections.abc import Iterable
from decimal import Decimal
from json.decoder import JSONDecodeError
-from typing import Any, Callable, Dict, Iterable, List, Optional, cast
+from typing import Any, Callable, Optional, cast
from urllib.parse import urlencode, urlparse
import Adyen
@@ -245,7 +246,7 @@ def handle_not_created_order(notification, payment, checkout, kind, manager):
return None
-def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayConfig):
+def handle_authorization(notification: dict[str, Any], gateway_config: GatewayConfig):
"""Handle authorization notification.
Handler for processing an authorization notification from Adyen. The notification
@@ -350,7 +351,7 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
def handle_cancellation(
- notification: Dict[str, Any],
+ notification: dict[str, Any],
_gateway_config: GatewayConfig,
):
# https://docs.adyen.com/checkout/cancel#cancellation-notifciation
@@ -384,7 +385,7 @@ def handle_cancellation(
def handle_cancel_or_refund(
- notification: Dict[str, Any], gateway_config: GatewayConfig
+ notification: dict[str, Any], gateway_config: GatewayConfig
):
# https://docs.adyen.com/checkout/cancel-or-refund#cancel-or-refund-notification
additional_data = notification.get("additionalData")
@@ -397,7 +398,7 @@ def handle_cancel_or_refund(
handle_cancellation(notification, gateway_config)
-def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
+def handle_capture(notification: dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/capture#capture-notification
transaction_id = notification.get("pspReference")
graphql_payment_id = notification.get("merchantReference")
@@ -447,7 +448,7 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)
-def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
+def handle_failed_capture(notification: dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/capture#failed-capture
transaction_id = notification.get("pspReference")
payment = get_payment(
@@ -475,7 +476,7 @@ def handle_failed_capture(notification: Dict[str, Any], _gateway_config: Gateway
create_payment_notification_for_order(payment, msg, None, True)
-def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
+def handle_pending(notification: dict[str, Any], gateway_config: GatewayConfig):
# https://docs.adyen.com/development-resources/webhooks/understand-notifications#
# event-codes"
transaction_id = notification.get("pspReference")
@@ -500,7 +501,7 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
)
-def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
+def handle_refund(notification: dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/refund#refund-notification
transaction_id = notification.get("pspReference")
payment = get_payment(
@@ -544,7 +545,7 @@ def _get_kind(transaction: Optional[Transaction]) -> str:
return TransactionKind.CAPTURE
-def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayConfig):
+def handle_failed_refund(notification: dict[str, Any], gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/refund#failed-refund
transaction_id = notification.get("pspReference")
payment = get_payment(
@@ -610,7 +611,7 @@ def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayCo
def handle_reversed_refund(
- notification: Dict[str, Any], _gateway_config: GatewayConfig
+ notification: dict[str, Any], _gateway_config: GatewayConfig
):
# https://docs.adyen.com/checkout/refund#failed-refund
transaction_id = notification.get("pspReference")
@@ -641,14 +642,14 @@ def handle_reversed_refund(
def handle_refund_with_data(
- notification: Dict[str, Any], gateway_config: GatewayConfig
+ notification: dict[str, Any], gateway_config: GatewayConfig
):
# https://docs.adyen.com/checkout/refund#refund-with-data
handle_refund(notification, gateway_config)
def webhook_not_implemented(
- notification: Dict[str, Any], gateway_config: GatewayConfig
+ notification: dict[str, Any], gateway_config: GatewayConfig
):
adyen_id = notification.get("pspReference")
success = notification.get("success", True)
@@ -664,7 +665,7 @@ def webhook_not_implemented(
create_payment_notification_for_order(payment, msg, None, True)
-def handle_order_opened(notification: Dict[str, Any], gateway_config: GatewayConfig):
+def handle_order_opened(notification: dict[str, Any], gateway_config: GatewayConfig):
# From Adyen's documentation:
# Sent when the first payment for your payment request is a partial payment, and an
# order has been created.
@@ -674,8 +675,8 @@ def handle_order_opened(notification: Dict[str, Any], gateway_config: GatewayCon
def get_or_create_adyen_partial_payments(
- notification: Dict[str, Any], payment: Payment
-) -> Optional[List[Payment]]:
+ notification: dict[str, Any], payment: Payment
+) -> Optional[list[Payment]]:
"""Store basic data about partial payments created by Adyen.
This is a workaround for not supporting partial payments in Saleor. Adyen can
@@ -795,7 +796,7 @@ def refund_partial_payments(payments, config):
)
-def handle_order_closed(notification: Dict[str, Any], gateway_config: GatewayConfig):
+def handle_order_closed(notification: dict[str, Any], gateway_config: GatewayConfig):
# From Adyen's documentation:
# The success field informs you of the outcome of the shopper's last payment when
# paying for an order in partial payments.
@@ -900,7 +901,7 @@ EVENT_MAP = {
def validate_hmac_signature(
- notification: Dict[str, Any], gateway_config: "GatewayConfig"
+ notification: dict[str, Any], gateway_config: "GatewayConfig"
) -> bool:
hmac_signature: Optional[str] = notification.get("additionalData", {}).get(
"hmacSignature"
@@ -966,7 +967,7 @@ def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") ->
def validate_merchant_account(
- notification: Dict[str, Any], gateway_config: "GatewayConfig"
+ notification: dict[str, Any], gateway_config: "GatewayConfig"
):
merchant_account_code = notification.get("merchantAccountCode")
return merchant_account_code == gateway_config.connection_params.get(
diff --git a/saleor/payment/gateways/authorize_net/__init__.py b/saleor/payment/gateways/authorize_net/__init__.py
index a8ebd514ad..d0598ef0c5 100644
--- a/saleor/payment/gateways/authorize_net/__init__.py
+++ b/saleor/payment/gateways/authorize_net/__init__.py
@@ -1,5 +1,5 @@
import json
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any, Optional, Union
from authorizenet import apicontractsv1
from authorizenet.apicontrollers import (
@@ -23,7 +23,7 @@ from ...interface import (
def authenticate_test(
name: str, transaction_key: str, use_sandbox: bool
-) -> Tuple[bool, str]:
+) -> tuple[bool, str]:
"""Check if credentials are correct.
This API is not present in the authorizenet Python package.
@@ -250,7 +250,7 @@ def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResp
def list_client_sources(
config: GatewayConfig, customer_id: str
-) -> List[CustomerSource]:
+) -> list[CustomerSource]:
merchant_auth = _get_merchant_auth(config.connection_params)
get_customer_profile = apicontractsv1.getCustomerProfileRequest()
@@ -351,7 +351,7 @@ def refund(
def _handle_authorize_net_response(
response: ObjectifiedElement,
-) -> Tuple[bool, Optional[str], str, Any, Any]:
+) -> tuple[bool, Optional[str], str, Any, Any]:
success = False
error: Optional[str] = None
transaction_id: Optional[int] = None
@@ -416,14 +416,14 @@ def _authorize_net_account_to_payment_method_info(
return None
-def _get_merchant_auth(connection_params: Dict[str, Any]):
+def _get_merchant_auth(connection_params: dict[str, Any]):
merchant_auth = apicontractsv1.merchantAuthenticationType()
merchant_auth.name = connection_params.get("api_login_id")
merchant_auth.transactionKey = connection_params.get("transaction_key")
return merchant_auth
-def _make_request(create_transaction_request, connection_params: Dict[str, Any]):
+def _make_request(create_transaction_request, connection_params: dict[str, Any]):
"""Create an auth.net transaction controller and execute the request.
Returns auth.net response object
@@ -448,7 +448,7 @@ def _normalize_last_4(account_number: str):
return account_number.strip("X")
-def _normalize_card_expiration(expiration_date: str) -> List[Optional[int]]:
+def _normalize_card_expiration(expiration_date: str) -> list[Optional[int]]:
"""Convert authorize.net combined expiration date into month and year.
Example: 2021-02 > [2021, 2]
diff --git a/saleor/payment/gateways/authorize_net/plugin.py b/saleor/payment/gateways/authorize_net/plugin.py
index 561aca60dc..d4c648a410 100644
--- a/saleor/payment/gateways/authorize_net/plugin.py
+++ b/saleor/payment/gateways/authorize_net/plugin.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from django.core.exceptions import ValidationError
@@ -184,7 +184,7 @@ class AuthorizeNetGatewayPlugin(BasePlugin):
def list_payment_sources(
self, customer_id: str, previous_value
- ) -> List["CustomerSource"]:
+ ) -> list["CustomerSource"]:
if not self.active:
return previous_value
sources = list_client_sources(self._get_gateway_config(), customer_id)
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index 3accb786bf..7cd28df664 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -1,4 +1,4 @@
-from typing import Dict, List, Optional
+from typing import Optional
import braintree as braintree_sdk
import opentracing
@@ -28,8 +28,8 @@ ERROR_CODES_WHITELIST = {
}
-def get_billing_data(payment_information: PaymentData) -> Dict:
- billing: Dict[str, str] = {}
+def get_billing_data(payment_information: PaymentData) -> dict:
+ billing: dict[str, str] = {}
if payment_information.billing:
billing_info = payment_information.billing
billing = {
@@ -46,7 +46,7 @@ def get_billing_data(payment_information: PaymentData) -> Dict:
return billing
-def get_customer_data(payment_information: PaymentData) -> Dict:
+def get_customer_data(payment_information: PaymentData) -> dict:
"""Provide customer info, use only for new customer creation."""
return {
"order_id": payment_information.graphql_payment_id,
@@ -56,7 +56,7 @@ def get_customer_data(payment_information: PaymentData) -> Dict:
}
-def get_error_for_client(errors: List) -> str:
+def get_error_for_client(errors: list) -> str:
"""Filter all error messages and decides which one is visible for the client."""
if not errors:
return ""
@@ -67,9 +67,9 @@ def get_error_for_client(errors: List) -> str:
return default_msg
-def extract_gateway_response(braintree_result) -> Dict:
+def extract_gateway_response(braintree_result) -> dict:
"""Extract data from Braintree response that will be stored locally."""
- errors: List[Optional[Dict[str, str]]] = []
+ errors: list[Optional[dict[str, str]]] = []
if not braintree_result.is_success:
errors = [
{"code": error.code, "message": error.message}
@@ -348,7 +348,7 @@ def process_payment(
def list_client_sources(
config: GatewayConfig, customer_id: str
-) -> List[CustomerSource]:
+) -> list[CustomerSource]:
gateway = get_braintree_gateway(**config.connection_params)
with opentracing.global_tracer().start_active_span(
"braintree.customer.find"
diff --git a/saleor/payment/gateways/braintree/plugin.py b/saleor/payment/gateways/braintree/plugin.py
index 0e54e3f29f..b4c20dbafa 100644
--- a/saleor/payment/gateways/braintree/plugin.py
+++ b/saleor/payment/gateways/braintree/plugin.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField
@@ -148,7 +148,7 @@ class BraintreeGatewayPlugin(BasePlugin):
def list_payment_sources(
self, customer_id: str, previous_value
- ) -> List["CustomerSource"]:
+ ) -> list["CustomerSource"]:
if not self.active:
return previous_value
sources = list_client_sources(self._get_gateway_config(), customer_id)
diff --git a/saleor/payment/gateways/np_atobarai/__init__.py b/saleor/payment/gateways/np_atobarai/__init__.py
index e25d2aea25..a8c0da0338 100644
--- a/saleor/payment/gateways/np_atobarai/__init__.py
+++ b/saleor/payment/gateways/np_atobarai/__init__.py
@@ -1,6 +1,5 @@
import logging
import os
-from typing import List
from graphene import Node
@@ -21,7 +20,7 @@ from .utils import (
logger = logging.getLogger(__name__)
-def parse_errors(errors: List[str]) -> str:
+def parse_errors(errors: list[str]) -> str:
# Field error of Transaction db model has max length of 256
# Error codes have max length of 11
# We are limiting errors to maximum of 11 codes, because:
diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.py
index 5f06a8fb01..87f332baf6 100644
--- a/saleor/payment/gateways/np_atobarai/api.py
+++ b/saleor/payment/gateways/np_atobarai/api.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import List, Optional, Tuple
+from typing import Optional
from ....order.models import Fulfillment
from ...interface import PaymentData
@@ -94,7 +94,7 @@ def change_transaction(
config: ApiConfig,
payment: Payment,
payment_information: PaymentData,
- goods: List[dict],
+ goods: list[dict],
billed_amount: Decimal,
) -> PaymentResult:
"""Change transaction.
@@ -152,7 +152,7 @@ def reregister_transaction_for_partial_return(
payment_information: PaymentData,
shipping_company_code: Optional[str],
tracking_number: Optional[str],
- goods: List[dict],
+ goods: list[dict],
billed_amount: Decimal,
) -> PaymentResult:
"""Change transaction.
@@ -209,7 +209,7 @@ def reregister_transaction_for_partial_return(
def report_fulfillment(
config: ApiConfig, payment: Payment, fulfillment: Fulfillment
-) -> Tuple[List[str], bool]:
+) -> tuple[list[str], bool]:
"""Report fulfillment.
After this action, given payment is captured in NP Atobarai.
diff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.py
index e27734c8c7..f5c95797c9 100644
--- a/saleor/payment/gateways/np_atobarai/api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -1,6 +1,7 @@
import logging
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
import requests
from django.conf import settings
@@ -144,7 +145,7 @@ def _get_goods_name(line: PaymentLineData, config: "ApiConfig") -> str:
def _get_voucher_and_shipping_goods(
config: "ApiConfig",
payment_information: PaymentData,
-) -> List[dict]:
+) -> list[dict]:
"""Convert voucher and shipping amount into NP Atobarai goods lines."""
goods_lines = []
voucher_amount = payment_information.lines_data.voucher_amount
@@ -177,7 +178,7 @@ def get_goods_with_refunds(
config: "ApiConfig",
payment: Payment,
payment_information: PaymentData,
-) -> Tuple[List[dict], Decimal]:
+) -> tuple[list[dict], Decimal]:
"""Combine PaymentLinesData and RefundData into NP Atobarai's goods list.
Used for payment updates.
@@ -233,7 +234,7 @@ def get_goods_with_refunds(
return goods_lines, billed_amount
-def get_goods(config: "ApiConfig", payment_information: PaymentData) -> List[dict]:
+def get_goods(config: "ApiConfig", payment_information: PaymentData) -> list[dict]:
"""Convert PaymentLinesData into NP Atobarai's goods list.
Used for initial payment registration only.
@@ -257,7 +258,7 @@ def register(
config: "ApiConfig",
payment_information: "PaymentData",
billed_amount: Optional[int] = None,
- goods: Optional[List[dict]] = None,
+ goods: Optional[list[dict]] = None,
) -> NPResponse:
if billed_amount is None:
billed_amount = format_price(
diff --git a/saleor/payment/gateways/np_atobarai/api_types.py b/saleor/payment/gateways/np_atobarai/api_types.py
index 549dd58a8d..e787516d9b 100644
--- a/saleor/payment/gateways/np_atobarai/api_types.py
+++ b/saleor/payment/gateways/np_atobarai/api_types.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
from enum import Enum
-from typing import Dict, List, NamedTuple, Optional
+from typing import NamedTuple, Optional
from .const import (
FILL_MISSING_ADDRESS,
@@ -17,7 +17,7 @@ from .const import (
class NPResponse(NamedTuple):
result: dict
- error_codes: List[str]
+ error_codes: list[str]
def error_np_response(error_message: str) -> NPResponse:
@@ -46,15 +46,15 @@ class PaymentStatus(str, Enum):
class PaymentResult:
status: PaymentStatus
psp_reference: Optional[str] = None
- raw_response: Dict[str, str] = field(default_factory=dict)
- errors: List[str] = field(default_factory=list)
+ raw_response: dict[str, str] = field(default_factory=dict)
+ errors: list[str] = field(default_factory=list)
def error_payment_result(error_message: str) -> PaymentResult:
return PaymentResult(status=PaymentStatus.FAILED, errors=[error_message])
-def errors_payment_result(errors: List[str]) -> PaymentResult:
+def errors_payment_result(errors: list[str]) -> PaymentResult:
return PaymentResult(status=PaymentStatus.FAILED, errors=errors)
diff --git a/saleor/payment/gateways/np_atobarai/errors.py b/saleor/payment/gateways/np_atobarai/errors.py
index dbfbcd2e90..8c49c396ff 100644
--- a/saleor/payment/gateways/np_atobarai/errors.py
+++ b/saleor/payment/gateways/np_atobarai/errors.py
@@ -1,4 +1,4 @@
-from typing import Iterable, List
+from collections.abc import Iterable
TRANSACTION_REGISTRATION = "TR"
TRANSACTION_CANCELLATION = "TC"
@@ -10,7 +10,7 @@ def add_action_to_code(action: str, error_code: str) -> str:
return f"{action}#{error_code}"
-def get_error_messages_from_codes(action: str, error_codes: Iterable[str]) -> List[str]:
+def get_error_messages_from_codes(action: str, error_codes: Iterable[str]) -> list[str]:
return [add_action_to_code(action, code) for code in error_codes]
diff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.py
index 3b5eb138a8..465a4d6ee7 100644
--- a/saleor/payment/gateways/np_atobarai/utils.py
+++ b/saleor/payment/gateways/np_atobarai/utils.py
@@ -1,8 +1,9 @@
from collections import defaultdict
+from collections.abc import Iterable
from contextlib import contextmanager
from decimal import Decimal
from itertools import chain
-from typing import Dict, Iterable, Optional
+from typing import Optional
from django.db.models import Q
@@ -109,7 +110,7 @@ def _get_refunded_fulfillment_lines_with_automatic_amount(
def create_refunded_lines(
order: Order,
refund_data: RefundData,
-) -> Dict[int, int]:
+) -> dict[int, int]:
"""Return all refunded product variants for specified order.
Takes into account previous refunds and current refund mutation parameters.
@@ -148,7 +149,7 @@ def create_refunded_lines(
current_order_refund_lines,
current_fulfillment_refund_lines,
)
- summed_refund_lines: Dict[int, int] = defaultdict(int)
+ summed_refund_lines: dict[int, int] = defaultdict(int)
for variant_id, quantity in refund_lines:
summed_refund_lines[variant_id] += quantity
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.py
index f5fc6dc190..dcb21b492f 100644
--- a/saleor/payment/gateways/razorpay/__init__.py
+++ b/saleor/payment/gateways/razorpay/__init__.py
@@ -1,7 +1,6 @@
import logging
import uuid
from decimal import Decimal
-from typing import Dict
import opentracing
import opentracing.tags
@@ -30,7 +29,7 @@ logger = logging.getLogger(__name__)
def _generate_response(
- payment_information: PaymentData, kind: str, data: Dict
+ payment_information: PaymentData, kind: str, data: dict
) -> GatewayResponse:
"""Generate Saleor transaction information from the payload or from passed data."""
return GatewayResponse(
@@ -63,7 +62,7 @@ def get_error_message_from_razorpay_error(exc: BaseException):
return errors.SERVER_ERROR
-def clean_razorpay_response(response: Dict):
+def clean_razorpay_response(response: dict):
"""Convert the Razorpay response to our internal representation.
As the Razorpay response payload contains the final amount
diff --git a/saleor/payment/gateways/stripe/deprecated/__init__.py b/saleor/payment/gateways/stripe/deprecated/__init__.py
index 31c733d6ae..57d2091dd5 100644
--- a/saleor/payment/gateways/stripe/deprecated/__init__.py
+++ b/saleor/payment/gateways/stripe/deprecated/__init__.py
@@ -1,5 +1,3 @@
-from typing import List
-
import opentracing
import opentracing.tags
import stripe
@@ -194,7 +192,7 @@ def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResp
def list_client_sources(
config: GatewayConfig, customer_id: str
-) -> List[CustomerSource]:
+) -> list[CustomerSource]:
client = _get_client(**config.connection_params)
with opentracing.global_tracer().start_active_span(
"stripe.PaymentMethod.list"
diff --git a/saleor/payment/gateways/stripe/deprecated/plugin.py b/saleor/payment/gateways/stripe/deprecated/plugin.py
index 87271fb835..0bef7322bc 100644
--- a/saleor/payment/gateways/stripe/deprecated/plugin.py
+++ b/saleor/payment/gateways/stripe/deprecated/plugin.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField
@@ -120,7 +120,7 @@ class DeprecatedStripeGatewayPlugin(BasePlugin):
def list_payment_sources(
self, customer_id: str, previous_value
- ) -> List["CustomerSource"]:
+ ) -> list["CustomerSource"]:
if not self.active:
return previous_value
sources = list_client_sources(self._get_gateway_config(), customer_id)
diff --git a/saleor/payment/gateways/stripe/deprecated/utils.py b/saleor/payment/gateways/stripe/deprecated/utils.py
index 8bdd476125..73cc836962 100644
--- a/saleor/payment/gateways/stripe/deprecated/utils.py
+++ b/saleor/payment/gateways/stripe/deprecated/utils.py
@@ -1,5 +1,4 @@
from decimal import Decimal
-from typing import Dict
from django_countries import countries
@@ -83,7 +82,7 @@ def get_payment_billing_fullname(payment_information: PaymentData) -> str:
return f"{payment_billing.last_name} {payment_billing.first_name}"
-def shipping_to_stripe_dict(shipping: AddressData) -> Dict:
+def shipping_to_stripe_dict(shipping: AddressData) -> dict:
return {
"name": shipping.first_name + " " + shipping.last_name,
"phone": shipping.phone,
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.py
index 79869cd30b..1fe081310f 100644
--- a/saleor/payment/gateways/stripe/plugin.py
+++ b/saleor/payment/gateways/stripe/plugin.py
@@ -1,5 +1,5 @@
import logging
-from typing import TYPE_CHECKING, List, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
@@ -155,7 +155,7 @@ class StripeGatewayPlugin(BasePlugin):
def _get_transaction_details_for_stripe_status(
self, status: str
- ) -> Tuple[str, bool]:
+ ) -> tuple[str, bool]:
kind = TransactionKind.AUTH
action_required = True
@@ -457,7 +457,7 @@ class StripeGatewayPlugin(BasePlugin):
def list_payment_sources(
self, customer_id: str, previous_value
- ) -> List[CustomerSource]:
+ ) -> list[CustomerSource]:
if not self.active:
return previous_value
payment_methods, error = list_customer_payment_methods(
diff --git a/saleor/payment/gateways/stripe/stripe_api.py b/saleor/payment/gateways/stripe/stripe_api.py
index f4dfc17695..e428aa1660 100644
--- a/saleor/payment/gateways/stripe/stripe_api.py
+++ b/saleor/payment/gateways/stripe/stripe_api.py
@@ -1,7 +1,7 @@
import logging
from contextlib import contextmanager
from decimal import Decimal
-from typing import Dict, List, Optional, Tuple
+from typing import Optional
from urllib.parse import urljoin
import stripe
@@ -131,9 +131,9 @@ def create_payment_intent(
metadata: Optional[dict] = None,
setup_future_usage: Optional[str] = None,
off_session: Optional[bool] = None,
- payment_method_types: Optional[List[str]] = None,
+ payment_method_types: Optional[list[str]] = None,
customer_email: Optional[str] = None,
-) -> Tuple[Optional[StripeObject], Optional[StripeError]]:
+) -> tuple[Optional[StripeObject], Optional[StripeError]]:
capture_method = AUTOMATIC_CAPTURE_METHOD if auto_capture else MANUAL_CAPTURE_METHOD
additional_params = {}
@@ -179,7 +179,7 @@ def create_payment_intent(
def update_payment_method(
api_key: str,
payment_method_id: str,
- metadata: Dict[str, str],
+ metadata: dict[str, str],
):
with stripe_opentracing_trace("stripe.PaymentMethod.modify"):
try:
@@ -197,7 +197,7 @@ def update_payment_method(
def list_customer_payment_methods(
api_key: str, customer_id: str
-) -> Tuple[Optional[StripeObject], Optional[StripeError]]:
+) -> tuple[Optional[StripeObject], Optional[StripeError]]:
try:
with stripe_opentracing_trace("stripe.PaymentMethod.list"):
payment_methods = stripe.PaymentMethod.list(
@@ -212,7 +212,7 @@ def list_customer_payment_methods(
def retrieve_payment_intent(
api_key: str, payment_intent_id: str
-) -> Tuple[Optional[StripeObject], Optional[StripeError]]:
+) -> tuple[Optional[StripeObject], Optional[StripeError]]:
try:
with stripe_opentracing_trace("stripe.PaymentIntent.retrieve"):
payment_intent = stripe.PaymentIntent.retrieve(
@@ -230,7 +230,7 @@ def retrieve_payment_intent(
def capture_payment_intent(
api_key: str, payment_intent_id: str, amount_to_capture: int
-) -> Tuple[Optional[StripeObject], Optional[StripeError]]:
+) -> tuple[Optional[StripeObject], Optional[StripeError]]:
try:
with stripe_opentracing_trace("stripe.PaymentIntent.capture"):
payment_intent = stripe.PaymentIntent.capture(
@@ -249,7 +249,7 @@ def capture_payment_intent(
def refund_payment_intent(
api_key: str, payment_intent_id: str, amount_to_refund: int
-) -> Tuple[Optional[StripeObject], Optional[StripeError]]:
+) -> tuple[Optional[StripeObject], Optional[StripeError]]:
try:
with stripe_opentracing_trace("stripe.Refund.create"):
refund = stripe.Refund.create(
@@ -268,7 +268,7 @@ def refund_payment_intent(
def cancel_payment_intent(
api_key: str, payment_intent_id: str
-) -> Tuple[Optional[StripeObject], Optional[StripeError]]:
+) -> tuple[Optional[StripeObject], Optional[StripeError]]:
try:
with stripe_opentracing_trace("stripe.PaymentIntent.cancel"):
payment_intent = stripe.PaymentIntent.cancel(
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 7c5c010e5d..691d38ed07 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -1,5 +1,5 @@
import logging
-from typing import List, Optional
+from typing import Optional
from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
@@ -281,7 +281,7 @@ def update_payment_method_details_from_intent(
payment: Payment, payment_intent: StripeObject
):
if payment_method_info := get_payment_method_details(payment_intent):
- changed_fields: List[str] = []
+ changed_fields: list[str] = []
update_payment_method_details(payment, payment_method_info, changed_fields)
if changed_fields:
payment.save(update_fields=changed_fields)
diff --git a/saleor/payment/gateways/utils.py b/saleor/payment/gateways/utils.py
index 3246b16540..4f928466a3 100644
--- a/saleor/payment/gateways/utils.py
+++ b/saleor/payment/gateways/utils.py
@@ -1,11 +1,11 @@
import warnings
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..interface import GatewayConfig
-def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List[str]:
+def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> list[str]:
"""Return supported currencies for given gateway configuration.
If supported currencies are not specified, the default currency is used
@@ -13,7 +13,7 @@ def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List
"""
supp_currencies = config.supported_currencies
if not supp_currencies:
- currencies: List[str] = []
+ currencies: list[str] = []
warnings.warn(
f"Supported currencies not configured for {gateway_name}, "
"please configure supported currencies for this gateway."
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index a01134512d..be9e086ed8 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -3,7 +3,7 @@ from datetime import datetime
from decimal import Decimal
from enum import Enum
from functools import cached_property
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Optional, Union
from ..order import FulfillmentLineData
from ..order.fetch import OrderLineInfo
@@ -16,8 +16,8 @@ if TYPE_CHECKING:
from ..checkout.models import Checkout
from ..order.models import Order, OrderGrantedRefund
-JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
-JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
+JSONValue = Union[str, int, float, bool, None, dict[str, Any], list[Any]]
+JSONType = Union[dict[str, JSONValue], list[JSONValue]]
@dataclass
@@ -59,8 +59,8 @@ class PaymentGateway:
id: str
name: str
- currencies: List[str]
- config: List[Dict[str, Any]]
+ currencies: list[str]
+ config: list[dict[str, Any]]
@dataclass
@@ -101,7 +101,7 @@ class PaymentMethodData:
type: str
external_id: str
gateway: PaymentGateway
- supported_payment_flows: List[str] = field(default_factory=list)
+ supported_payment_flows: list[str] = field(default_factory=list)
credit_card_info: Optional[PaymentMethodCreditCardInfo] = None
name: Optional[str] = None
data: Optional[JSONType] = None
@@ -130,7 +130,7 @@ class TransactionRequestEventResponse:
@dataclass
class TransactionRequestResponse:
psp_reference: Optional[str]
- available_actions: Optional[List[str]] = None
+ available_actions: Optional[list[str]] = None
event: Optional["TransactionRequestEventResponse"] = None
@@ -140,13 +140,13 @@ class TransactionData:
is_success: bool
kind: str
gateway_response: JSONType
- amount: Dict[str, str]
+ amount: dict[str, str]
@dataclass
class PaymentGatewayData:
app_identifier: str
- data: Optional[Dict[Any, Any]] = None
+ data: Optional[dict[Any, Any]] = None
error: Optional[str] = None
@@ -169,7 +169,7 @@ class TransactionSessionData:
@dataclass
class TransactionSessionResult:
app_identifier: str
- response: Optional[Dict[Any, Any]] = None
+ response: Optional[dict[Any, Any]] = None
error: Optional[str] = None
@@ -293,7 +293,7 @@ class GatewayResponse:
error: Optional[str]
customer_id: Optional[str] = None
payment_method_info: Optional[PaymentMethodInfo] = None
- raw_response: Optional[Dict[str, str]] = None
+ raw_response: Optional[dict[str, str]] = None
action_required_data: Optional[JSONType] = None
# Some gateway can process transaction asynchronously. This value define if we
# should create new transaction based on this response
@@ -337,13 +337,13 @@ class PaymentLineData:
class PaymentLinesData:
shipping_amount: Decimal
voucher_amount: Decimal
- lines: List[PaymentLineData]
+ lines: list[PaymentLineData]
@dataclass
class RefundData:
- order_lines_to_refund: List[OrderLineInfo] = field(default_factory=list)
- fulfillment_lines_to_refund: List[FulfillmentLineData] = field(default_factory=list)
+ order_lines_to_refund: list[OrderLineInfo] = field(default_factory=list)
+ fulfillment_lines_to_refund: list[FulfillmentLineData] = field(default_factory=list)
refund_shipping_costs: bool = False
refund_amount_is_automatically_calculated: bool = True
@@ -373,12 +373,12 @@ class PaymentData:
data: Optional[dict] = None
graphql_customer_id: Optional[str] = None
checkout_token: Optional[str] = None
- checkout_metadata: Optional[Dict] = None
+ checkout_metadata: Optional[dict] = None
store_payment_method: StorePaymentMethodEnum = StorePaymentMethodEnum.NONE
- payment_metadata: Dict[str, str] = field(default_factory=dict)
+ payment_metadata: dict[str, str] = field(default_factory=dict)
psp_reference: Optional[str] = None
refund_data: Optional[RefundData] = None
- transactions: List[TransactionData] = field(default_factory=list)
+ transactions: list[TransactionData] = field(default_factory=list)
# Optional, lazy-evaluated gateway arguments
_resolve_lines_data: InitVar[Callable[[], PaymentLinesData]] = None
@@ -412,7 +412,7 @@ class GatewayConfig:
supported_currencies: str
# Each gateway has different connection data so we are not able to create
# a unified structure
- connection_params: Dict[str, Any]
+ connection_params: dict[str, Any]
store_customer: bool = False
require_3d_secure: bool = False
@@ -424,7 +424,7 @@ class CustomerSource:
id: str
gateway: str
credit_card_info: Optional[PaymentMethodInfo] = None
- metadata: Optional[Dict[str, str]] = None
+ metadata: Optional[dict[str, str]] = None
@dataclass
diff --git a/saleor/payment/model_helpers.py b/saleor/payment/model_helpers.py
index 695a34a378..e0d3e655d6 100644
--- a/saleor/payment/model_helpers.py
+++ b/saleor/payment/model_helpers.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from operator import attrgetter
-from typing import TYPE_CHECKING, Iterable
+from typing import TYPE_CHECKING
from ..core.taxes import zero_money, zero_taxed_money
from .models import Payment
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index e8b425c836..b6e8a0a0c9 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -663,12 +663,12 @@ def test_validate_gateway_response_incorrect_transaction_kind(gateway_response):
validate_gateway_response(gateway_response)
assert str(e.value) == (
- "Gateway response kind must be one of {}".format(sorted(ALLOWED_GATEWAY_KINDS))
+ f"Gateway response kind must be one of {sorted(ALLOWED_GATEWAY_KINDS)}"
)
def test_validate_gateway_response_not_json_serializable(gateway_response):
- class CustomClass(object):
+ class CustomClass:
pass
gateway_response.raw_response = CustomClass()
diff --git a/saleor/payment/transaction_item_calculations.py b/saleor/payment/transaction_item_calculations.py
index aa5f6fa2ac..8b9d7e1d3b 100644
--- a/saleor/payment/transaction_item_calculations.py
+++ b/saleor/payment/transaction_item_calculations.py
@@ -1,7 +1,8 @@
from collections import defaultdict
+from collections.abc import Iterable
from dataclasses import dataclass, field
from decimal import Decimal
-from typing import Dict, Iterable, List, Optional, cast
+from typing import Optional, cast
from . import TransactionEventType
from .models import TransactionEvent, TransactionItem
@@ -46,17 +47,17 @@ AUTHORIZATION_EVENTS = [
@dataclass
class ActionEventMap:
- without_psp_reference: List[TransactionEvent]
- authorization: Dict[PSPReference, AuthorizationEvents] = field(
+ without_psp_reference: list[TransactionEvent]
+ authorization: dict[PSPReference, AuthorizationEvents] = field(
default_factory=lambda: defaultdict(AuthorizationEvents)
)
- charge: Dict[PSPReference, ChargeEvents] = field(
+ charge: dict[PSPReference, ChargeEvents] = field(
default_factory=lambda: defaultdict(ChargeEvents)
)
- refund: Dict[PSPReference, RefundEvents] = field(
+ refund: dict[PSPReference, RefundEvents] = field(
default_factory=lambda: defaultdict(RefundEvents)
)
- cancel: Dict[PSPReference, CancelEvents] = field(
+ cancel: dict[PSPReference, CancelEvents] = field(
default_factory=lambda: defaultdict(CancelEvents)
)
@@ -211,8 +212,8 @@ def _recalculate_cancel_amounts(
)
-def _get_authorize_events(events: Iterable[TransactionEvent]) -> List[TransactionEvent]:
- authorize_events: List[TransactionEvent] = [
+def _get_authorize_events(events: Iterable[TransactionEvent]) -> list[TransactionEvent]:
+ authorize_events: list[TransactionEvent] = [
event for event in events if event.type in AUTHORIZATION_EVENTS
]
auth_adjustment_event: Optional[TransactionEvent] = next(
@@ -233,7 +234,7 @@ def _get_authorize_events(events: Iterable[TransactionEvent]) -> List[Transactio
def _handle_events_without_psp_reference(
- transaction: TransactionItem, events: List[TransactionEvent]
+ transaction: TransactionItem, events: list[TransactionEvent]
):
"""Calculate the amounts for event without psp reference.
@@ -265,7 +266,7 @@ def _handle_events_without_psp_reference(
def _initilize_action_map(events: Iterable[TransactionEvent]) -> ActionEventMap:
event_map = ActionEventMap(without_psp_reference=[])
authorize_events = _get_authorize_events(events)
- events_without_authorize: List[TransactionEvent] = [
+ events_without_authorize: list[TransactionEvent] = [
event for event in events if event.type not in AUTHORIZATION_EVENTS
]
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 034f6833e0..213f948305 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -3,7 +3,7 @@ import json
import logging
from datetime import datetime
from decimal import Decimal
-from typing import Any, Dict, Optional, Union, cast, overload
+from typing import Any, Optional, Union, cast, overload
import graphene
from aniso8601 import parse_datetime
@@ -260,13 +260,13 @@ def create_payment(
email: str,
customer_ip_address: Optional[str] = None,
payment_token: Optional[str] = None,
- extra_data: Optional[Dict] = None,
+ extra_data: Optional[dict] = None,
checkout: Optional[Checkout] = None,
order: Optional[Order] = None,
return_url: Optional[str] = None,
external_reference: Optional[str] = None,
store_payment_method: str = StorePaymentMethod.NONE,
- metadata: Optional[Dict[str, str]] = None,
+ metadata: Optional[dict[str, str]] = None,
) -> Payment:
"""Create a payment instance.
@@ -454,9 +454,7 @@ def validate_gateway_response(response: GatewayResponse):
if response.kind not in ALLOWED_GATEWAY_KINDS:
raise GatewayError(
- "Gateway response kind must be one of {}".format(
- sorted(ALLOWED_GATEWAY_KINDS)
- )
+ f"Gateway response kind must be one of {sorted(ALLOWED_GATEWAY_KINDS)}"
)
try:
@@ -1039,7 +1037,7 @@ def _create_event_from_response(
def _get_parsed_transaction_action_data(
- transaction_webhook_response: Optional[Dict[str, Any]],
+ transaction_webhook_response: Optional[dict[str, Any]],
event_type: str,
event_is_optional: bool = True,
psp_reference_is_optional: bool = False,
@@ -1079,7 +1077,7 @@ def create_transaction_event_for_transaction_session(
request_event: TransactionEvent,
app: App,
manager: "PluginsManager",
- transaction_webhook_response: Optional[Dict[str, Any]] = None,
+ transaction_webhook_response: Optional[dict[str, Any]] = None,
):
request_event_type = "session-request"
@@ -1197,7 +1195,7 @@ def create_transaction_event_for_transaction_session(
def create_transaction_event_from_request_and_webhook_response(
request_event: TransactionEvent,
app: App,
- transaction_webhook_response: Optional[Dict[str, Any]] = None,
+ transaction_webhook_response: Optional[dict[str, Any]] = None,
):
transaction_request_response, error_msg = _get_parsed_transaction_action_data(
transaction_webhook_response=transaction_webhook_response,
@@ -1293,7 +1291,7 @@ def _prepare_manual_event(
def prepare_manual_event(
events_to_create: list[TransactionEvent],
amount_field: str,
- money_data: Dict[str, Decimal],
+ money_data: dict[str, Decimal],
event_type: str,
transaction: TransactionItem,
user: Optional["User"],
@@ -1318,7 +1316,7 @@ def prepare_manual_event(
def create_manual_adjustment_events(
transaction: TransactionItem,
- money_data: Dict[str, Decimal],
+ money_data: dict[str, Decimal],
user: Optional["User"],
app: Optional["App"],
) -> list[TransactionEvent]:
diff --git a/saleor/permission/enums.py b/saleor/permission/enums.py
index 57872cfc36..a34a5e61e2 100644
--- a/saleor/permission/enums.py
+++ b/saleor/permission/enums.py
@@ -1,5 +1,5 @@
+from collections.abc import Iterable
from enum import Enum
-from typing import Iterable, List
from django.db.models import QuerySet
@@ -130,7 +130,7 @@ def get_permissions_enum_dict():
}
-def get_permissions_from_names(names: List[str]):
+def get_permissions_from_names(names: list[str]):
"""Convert list of permission names - ['MANAGE_ORDERS'] to Permission db objects."""
permissions = get_permissions_enum_dict()
return get_permissions([permissions[name].value for name in names])
@@ -159,7 +159,7 @@ def get_permissions(permissions=None):
return get_permissions_from_codenames(codenames)
-def get_permissions_from_codenames(permission_codenames: List[str]) -> QuerySet:
+def get_permissions_from_codenames(permission_codenames: list[str]) -> QuerySet:
return (
Permission.objects.filter(codename__in=permission_codenames)
.prefetch_related("content_type")
diff --git a/saleor/permission/management.py b/saleor/permission/management.py
index 19e6b878fc..4febcee9b1 100644
--- a/saleor/permission/management.py
+++ b/saleor/permission/management.py
@@ -19,7 +19,7 @@ def _get_builtin_permissions(opts): # noqa: D205, D212
perms.append(
(
get_permission_codename(action, opts),
- "Can %s %s" % (action, opts.verbose_name_raw),
+ f"Can {action} {opts.verbose_name_raw}",
)
)
return perms
diff --git a/saleor/permission/models.py b/saleor/permission/models.py
index bbe89636a5..268861555e 100644
--- a/saleor/permission/models.py
+++ b/saleor/permission/models.py
@@ -79,7 +79,7 @@ class Permission(models.Model):
ordering = ["content_type__app_label", "content_type__model", "codename"]
def __str__(self):
- return "%s | %s" % (self.content_type, self.name)
+ return f"{self.content_type} | {self.name}"
def natural_key(self):
return (self.codename,) + self.content_type.natural_key()
diff --git a/saleor/permission/tests/test_all_permissions_required.py b/saleor/permission/tests/test_all_permissions_required.py
index 57420b0b3f..5a7baf20ee 100644
--- a/saleor/permission/tests/test_all_permissions_required.py
+++ b/saleor/permission/tests/test_all_permissions_required.py
@@ -1,5 +1,6 @@
+from unittest.mock import Mock
+
import pytest
-from mock import Mock
from ..auth_filters import AuthorizationFilters
from ..enums import CheckoutPermissions
diff --git a/saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.py b/saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.py
index 6941e5be43..a36dae7d94 100644
--- a/saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.py
+++ b/saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.py
@@ -1,5 +1,6 @@
+from unittest.mock import Mock
+
import pytest
-from mock import Mock
from ..auth_filters import AuthorizationFilters
from ..enums import CheckoutPermissions, OrderPermissions
diff --git a/saleor/permission/utils.py b/saleor/permission/utils.py
index 64c8d19081..2052e10d8d 100644
--- a/saleor/permission/utils.py
+++ b/saleor/permission/utils.py
@@ -1,4 +1,5 @@
-from typing import TYPE_CHECKING, Iterable, Union
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Union
from .auth_filters import AuthorizationFilters, resolve_authorization_filter_fn
from .enums import AccountPermissions, BasePermissionEnum
diff --git a/saleor/plugins/__init__.py b/saleor/plugins/__init__.py
index 868e317e95..6826345c28 100644
--- a/saleor/plugins/__init__.py
+++ b/saleor/plugins/__init__.py
@@ -1,10 +1,9 @@
import importlib
-from typing import List
default_app_config = "saleor.plugins.apps.PluginConfig"
-def discover_plugins_modules(plugins: List[str]):
+def discover_plugins_modules(plugins: list[str]):
plugins_modules = []
for dotted_path in plugins:
try:
diff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.py
index 7f6948b2a1..eefe3755bc 100644
--- a/saleor/plugins/admin_email/plugin.py
+++ b/saleor/plugins/admin_email/plugin.py
@@ -1,6 +1,6 @@
import logging
from dataclasses import asdict
-from typing import List, Union
+from typing import Union
from django.conf import settings
from promise.promise import Promise
@@ -188,7 +188,7 @@ class AdminEmailPlugin(BasePlugin):
return self.configuration
def map_templates_to_configuration(
- email_templates: List["EmailTemplate"],
+ email_templates: list["EmailTemplate"],
) -> PluginConfigurationType:
email_template_by_name = {
email_template.name: email_template
diff --git a/saleor/plugins/apps.py b/saleor/plugins/apps.py
index e917d427f5..82a5478342 100644
--- a/saleor/plugins/apps.py
+++ b/saleor/plugins/apps.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from django.apps import AppConfig
from django.conf import settings
@@ -27,7 +27,7 @@ class PluginConfig(AppConfig):
self.check_plugin_fields(["PLUGIN_ID"], plugin)
- def check_plugin_fields(self, fields: List[str], plugin_class: "BasePlugin"):
+ def check_plugin_fields(self, fields: list[str], plugin_class: "BasePlugin"):
name = plugin_class.__name__ # type: ignore
for field in fields:
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 4d89214a86..4aa62cd6ac 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -1,9 +1,10 @@
import json
import logging
+from collections.abc import Iterable
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, Optional, Union, cast
from urllib.parse import urljoin
import opentracing
@@ -92,8 +93,8 @@ def get_api_url(use_sandbox=True) -> str:
def api_post_request(
- url: str, data: Dict[str, Any], config: AvataxConfiguration
-) -> Dict[str, Any]:
+ url: str, data: dict[str, Any], config: AvataxConfiguration
+) -> dict[str, Any]:
response = None
try:
auth = HTTPBasicAuth(config.username_or_account, config.password_or_license)
@@ -210,7 +211,7 @@ def _validate_checkout(
)
-def taxes_need_new_fetch(data: Dict[str, Any], cached_data) -> bool:
+def taxes_need_new_fetch(data: dict[str, Any], cached_data) -> bool:
"""Check if Avatax's taxes data need to be refetched.
The response from Avatax is stored in a cache. If an object doesn't exist in cache
@@ -226,7 +227,7 @@ def taxes_need_new_fetch(data: Dict[str, Any], cached_data) -> bool:
def append_line_to_data(
- data: List[Dict[str, Any]],
+ data: list[dict[str, Any]],
quantity: int,
amount: Decimal,
tax_code: str,
@@ -258,7 +259,7 @@ def append_line_to_data(
def append_shipping_to_data(
- data: List[Dict],
+ data: list[dict],
shipping_price_amount: Optional[Decimal],
shipping_tax_code: str,
prices_entered_with_tax: bool,
@@ -280,8 +281,8 @@ def generate_request_data_from_checkout_lines(
checkout_info: "CheckoutInfo",
lines_info: Iterable["CheckoutLineInfo"],
config: AvataxConfiguration,
-) -> List[Dict[str, Union[str, int, bool, None]]]:
- data: List[Dict[str, Union[str, int, bool, None]]] = []
+) -> list[dict[str, Union[str, int, bool, None]]]:
+ data: list[dict[str, Union[str, int, bool, None]]] = []
channel = checkout_info.channel
charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines_info)
@@ -368,8 +369,8 @@ def generate_request_data_from_checkout_lines(
def get_order_lines_data(
order: "Order", config: AvataxConfiguration, discounted: bool
-) -> List[Dict[str, Union[str, int, bool, None]]]:
- data: List[Dict[str, Union[str, int, bool, None]]] = []
+) -> list[dict[str, Union[str, int, bool, None]]]:
+ data: list[dict[str, Union[str, int, bool, None]]] = []
lines = order.lines.prefetch_related(
"variant__product__category",
"variant__product__collections",
@@ -451,9 +452,9 @@ def _is_single_location(ship_from, ship_to):
def generate_request_data(
transaction_type: str,
- lines: List[Dict[str, Any]],
+ lines: list[dict[str, Any]],
transaction_token: str,
- address: Dict[str, str],
+ address: dict[str, str],
customer_email: str,
config: AvataxConfiguration,
currency: str,
@@ -476,7 +477,7 @@ def generate_request_data(
"postalCode": address.get("postal_code"),
}
if _is_single_location(ship_from, ship_to):
- addresses: Dict[str, Dict] = {"singleLocation": ship_to}
+ addresses: dict[str, dict] = {"singleLocation": ship_to}
else:
addresses = {"shipFrom": ship_from, "shipTo": ship_to}
data = {
@@ -547,7 +548,7 @@ def generate_request_data_from_checkout(
def _fetch_new_taxes_data(
- data: Dict[str, Dict], data_cache_key: str, config: AvataxConfiguration
+ data: dict[str, dict], data_cache_key: str, config: AvataxConfiguration
):
transaction_url = urljoin(
get_api_url(config.use_sandbox), "transactions/createoradjust"
@@ -568,7 +569,7 @@ def _fetch_new_taxes_data(
def get_cached_response_or_fetch(
- data: Dict[str, Dict],
+ data: dict[str, dict],
token_in_cache: str,
config: AvataxConfiguration,
force_refresh: bool = False,
@@ -593,7 +594,7 @@ def get_checkout_tax_data(
checkout_info: "CheckoutInfo",
lines_info: Iterable["CheckoutLineInfo"],
config: AvataxConfiguration,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
data = generate_request_data_from_checkout(checkout_info, lines_info, config)
return get_cached_response_or_fetch(data, str(checkout_info.checkout.token), config)
@@ -630,7 +631,7 @@ def get_order_request_data(order: "Order", config: AvataxConfiguration):
def get_order_tax_data(
order: "Order", config: AvataxConfiguration, force_refresh=False
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
data = get_order_request_data(order, config)
response = get_cached_response_or_fetch(
data, f"order_{order.id}", config, force_refresh
@@ -640,7 +641,7 @@ def get_order_tax_data(
return response
-def generate_tax_codes_dict(response: Dict[str, Any]) -> Dict[str, str]:
+def generate_tax_codes_dict(response: dict[str, Any]) -> dict[str, str]:
tax_codes = {}
for line in response.get("value", []):
if line.get("isActive"):
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index b42f0c75b8..4dcd5e6410 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -1,8 +1,9 @@
import logging
+from collections.abc import Iterable
from dataclasses import asdict
from decimal import Decimal
from functools import partial
-from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Optional, Union
from urllib.parse import urljoin
import opentracing
@@ -239,7 +240,7 @@ class AvataxPlugin(BasePlugin):
self,
checkout_info: "CheckoutInfo",
currency: str,
- lines: List[Dict],
+ lines: list[dict],
shipping_price: Money,
) -> TaxedMoney:
discount_amount = Decimal(0.0)
@@ -393,7 +394,7 @@ class AvataxPlugin(BasePlugin):
@staticmethod
def _calculate_checkout_line_total_price(
- taxes_data: Dict[str, Any],
+ taxes_data: dict[str, Any],
item_code: str,
prices_entered_with_tax: Callable[[], bool],
# base_value should be provided as SimpleLazyObject
@@ -455,7 +456,7 @@ class AvataxPlugin(BasePlugin):
@staticmethod
def _calculate_order_line_total_price(
- taxes_data: Dict[str, Any],
+ taxes_data: dict[str, Any],
item_code: str,
prices_entered_with_tax: Callable[[], bool],
base_value: OrderTaxedPricesData,
@@ -634,7 +635,7 @@ class AvataxPlugin(BasePlugin):
zero_taxed_money(currency),
)
- def get_tax_rate_type_choices(self, previous_value: Any) -> List[TaxType]:
+ def get_tax_rate_type_choices(self, previous_value: Any) -> list[TaxType]:
if not self.active:
return previous_value
return [
@@ -733,7 +734,7 @@ class AvataxPlugin(BasePlugin):
@staticmethod
def _get_unit_tax_rate(
- response: Dict[str, Any],
+ response: dict[str, Any],
item_code: str,
base_rate: Decimal,
):
@@ -754,7 +755,7 @@ class AvataxPlugin(BasePlugin):
@staticmethod
def _get_shipping_tax_rate(
- response: Dict[str, Any],
+ response: dict[str, Any],
base_rate: Decimal,
):
if response is None:
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index eabd03489c..a2b8218d51 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1,3 +1,5 @@
+from collections import defaultdict
+from collections.abc import Iterable
from copy import copy
from dataclasses import dataclass
from decimal import Decimal
@@ -5,12 +7,7 @@ from typing import (
TYPE_CHECKING,
Any,
Callable,
- DefaultDict,
- Iterable,
- List,
Optional,
- Set,
- Tuple,
Union,
)
@@ -79,7 +76,7 @@ if TYPE_CHECKING:
from ..tax.models import TaxClass
from ..warehouse.models import Stock, Warehouse
-PluginConfigurationType = List[dict]
+PluginConfigurationType = list[dict]
RequestorOrLazyObject = Union[SimpleLazyObject, "Requestor"]
@@ -300,7 +297,7 @@ class BasePlugin:
calculate_checkout_line_total: Callable[
[
"CheckoutInfo",
- List["CheckoutLineInfo"],
+ list["CheckoutLineInfo"],
"CheckoutLineInfo",
Union["Address", None],
TaxedMoney,
@@ -312,7 +309,7 @@ class BasePlugin:
calculate_checkout_line_unit_price: Callable[
[
"CheckoutInfo",
- List["CheckoutLineInfo"],
+ list["CheckoutLineInfo"],
"CheckoutLineInfo",
Union["Address", None],
Any,
@@ -327,7 +324,7 @@ class BasePlugin:
calculate_checkout_shipping: Callable[
[
"CheckoutInfo",
- List["CheckoutLineInfo"],
+ list["CheckoutLineInfo"],
Union["Address", None],
TaxedMoney,
],
@@ -341,7 +338,7 @@ class BasePlugin:
calculate_checkout_total: Callable[
[
"CheckoutInfo",
- List["CheckoutLineInfo"],
+ list["CheckoutLineInfo"],
Union["Address", None],
TaxedMoney,
],
@@ -355,7 +352,7 @@ class BasePlugin:
calculate_checkout_subtotal: Callable[
[
"CheckoutInfo",
- List["CheckoutLineInfo"],
+ list["CheckoutLineInfo"],
Union["Address", None],
TaxedMoney,
],
@@ -391,7 +388,7 @@ class BasePlugin:
# Overwrite this method if you need to apply specific logic for the calculation
# of a order total. Return TaxedMoney.
calculate_order_total: Callable[
- ["Order", List["OrderLine"], TaxedMoney], TaxedMoney
+ ["Order", list["OrderLine"], TaxedMoney], TaxedMoney
]
capture_payment: Callable[["PaymentData", Any], GatewayResponse]
@@ -554,8 +551,8 @@ class BasePlugin:
#
# Overwrite this method if the plugin should validate the authentication data.
external_verify: Callable[
- [dict, WSGIRequest, Tuple[Union["User", None], dict]],
- Tuple[Union["User", None], dict],
+ [dict, WSGIRequest, tuple[Union["User", None], dict]],
+ tuple[Union["User", None], dict],
]
# Trigger when fulfillment is created.
@@ -585,7 +582,7 @@ class BasePlugin:
get_checkout_line_tax_rate: Callable[
[
"CheckoutInfo",
- List["CheckoutLineInfo"],
+ list["CheckoutLineInfo"],
"CheckoutLineInfo",
Union["Address", None],
Decimal,
@@ -621,7 +618,7 @@ class BasePlugin:
get_payment_config: Callable[[Any], Any]
get_shipping_methods_for_checkout: Callable[
- ["Checkout", Any], List["ShippingMethodData"]
+ ["Checkout", Any], list["ShippingMethodData"]
]
get_supported_currencies: Callable[[Any], Any]
@@ -637,7 +634,7 @@ class BasePlugin:
# assign tax categories to a product. It can be used by tax plugins to properly
# calculate taxes for products.
# Overwrite this method in case your plugin provides a list of tax categories.
- get_tax_rate_type_choices: Callable[[List["TaxType"]], List["TaxType"]]
+ get_tax_rate_type_choices: Callable[[list["TaxType"]], list["TaxType"]]
# Trigger when gift card is created.
#
@@ -695,7 +692,7 @@ class BasePlugin:
# Trigger after invoice is sent.
invoice_sent: Callable[["Invoice", str, Any], Any]
- list_payment_sources: Callable[[str, Any], List["CustomerSource"]]
+ list_payment_sources: Callable[[str, Any], list["CustomerSource"]]
list_stored_payment_methods: Callable[
["ListStoredPaymentMethodsRequestData", list["PaymentMethodData"]],
@@ -845,7 +842,7 @@ class BasePlugin:
#
# Overwrite this method if you need to trigger specific logic when an order
# is imported.
- order_bulk_created: Callable[[List["Order"], Any], Any]
+ order_bulk_created: Callable[[list["Order"], Any], Any]
# Trigger when page is created.
#
@@ -956,7 +953,7 @@ class BasePlugin:
#
# Overwrite this method if you need to trigger specific logic after a product is
# deleted.
- product_deleted: Callable[["Product", List[int], Any, None], Any]
+ product_deleted: Callable[["Product", list[int], Any, None], Any]
# Trigger when product is updated.
#
@@ -1041,20 +1038,20 @@ class BasePlugin:
# Trigger when sale is created.
#
# Overwrite this method if you need to trigger specific logic after sale is created.
- sale_created: Callable[["Promotion", DefaultDict[str, Set[str]], Any], Any]
+ sale_created: Callable[["Promotion", defaultdict[str, set[str]], Any], Any]
# Trigger when sale is deleted.
#
# Overwrite this method if you need to trigger specific logic after
# a sale is deleted.
- sale_deleted: Callable[["Promotion", DefaultDict[str, Set[str]], Any], Any]
+ sale_deleted: Callable[["Promotion", defaultdict[str, set[str]], Any], Any]
# Trigger when sale is updated.
#
# Overwrite this method if you need to trigger specific logic after
# a sale is updated.
sale_updated: Callable[
- ["Promotion", DefaultDict[str, Set[str]], DefaultDict[str, Set[str]], Any], Any
+ ["Promotion", defaultdict[str, set[str]], defaultdict[str, set[str]], Any], Any
]
# Trigger when promotion is created.
@@ -1276,7 +1273,7 @@ class BasePlugin:
checkout_info: Optional["CheckoutInfo"],
checkout_lines: Optional[Iterable["CheckoutLineInfo"]],
previous_value,
- ) -> List["PaymentGateway"]:
+ ) -> list["PaymentGateway"]:
payment_config = (
self.get_payment_config(previous_value)
if hasattr(self, "get_payment_config")
@@ -1299,7 +1296,7 @@ class BasePlugin:
@classmethod
def _update_config_items(
- cls, configuration_to_update: List[dict], current_config: List[dict]
+ cls, configuration_to_update: list[dict], current_config: list[dict]
):
config_structure: dict = (
cls.CONFIG_STRUCTURE if cls.CONFIG_STRUCTURE is not None else {}
diff --git a/saleor/plugins/email_common.py b/saleor/plugins/email_common.py
index 92377bbcfb..a8f2130a6b 100644
--- a/saleor/plugins/email_common.py
+++ b/saleor/plugins/email_common.py
@@ -5,7 +5,7 @@ import re
from dataclasses import asdict, dataclass
from decimal import Decimal, InvalidOperation
from email.headerregistry import Address
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Callable, Optional
import dateutil.parser
import html2text
@@ -150,7 +150,7 @@ def get_product_image_thumbnail(this, size: int, image_data):
def compare(this, val1, compare_operator, val2):
"""Compare two values based on the provided operator."""
- operators: Dict[str, Callable[[Any, Any], Any]] = {
+ operators: dict[str, Callable[[Any, Any], Any]] = {
"==": operator.eq,
"!=": operator.ne,
"<": operator.lt,
@@ -314,7 +314,7 @@ def validate_default_email_configuration(
def validate_format_of_provided_templates(
plugin_configuration: "PluginConfiguration",
- email_templates_data: List[Dict],
+ email_templates_data: list[dict],
):
"""Make sure that the templates provided by the user have the correct structure."""
configuration = plugin_configuration.configuration
@@ -323,7 +323,7 @@ def validate_format_of_provided_templates(
if not plugin_configuration.active:
return
compiler = pybars.Compiler()
- errors: Dict[str, ValidationError] = {}
+ errors: dict[str, ValidationError] = {}
for email_data in email_templates_data:
field: str = email_data["name"]
template_str = email_data.get("value")
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 2192e05df2..bae637f21a 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -1,16 +1,11 @@
from collections import defaultdict
+from collections.abc import Iterable
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
Callable,
- DefaultDict,
- Dict,
- Iterable,
- List,
Optional,
- Tuple,
- Type,
Union,
)
@@ -97,9 +92,9 @@ NotifyEventTypeChoice = str
class PluginsManager(PaymentInterface):
"""Base manager for handling plugins logic."""
- plugins_per_channel: Dict[str, List["BasePlugin"]] = {}
- global_plugins: List["BasePlugin"] = []
- all_plugins: List["BasePlugin"] = []
+ plugins_per_channel: dict[str, list["BasePlugin"]] = {}
+ global_plugins: list["BasePlugin"] = []
+ all_plugins: list["BasePlugin"] = []
@property
def database(self):
@@ -111,7 +106,7 @@ class PluginsManager(PaymentInterface):
def _load_plugin(
self,
- PluginClass: Type["BasePlugin"],
+ PluginClass: type["BasePlugin"],
db_configs_map: dict,
channel: Optional["Channel"] = None,
requestor_getter=None,
@@ -136,7 +131,7 @@ class PluginsManager(PaymentInterface):
allow_replica=allow_replica,
)
- def __init__(self, plugins: List[str], requestor_getter=None, allow_replica=True):
+ def __init__(self, plugins: list[str], requestor_getter=None, allow_replica=True):
with opentracing.global_tracer().start_active_span("PluginsManager.__init__"):
self._allow_replica = allow_replica
self.all_plugins = []
@@ -181,7 +176,7 @@ class PluginsManager(PaymentInterface):
plugin_manager_configs = PluginConfiguration.objects.using(
self.database
).all()
- channel_configs: DefaultDict[Channel, Dict] = defaultdict(dict)
+ channel_configs: defaultdict[Channel, dict] = defaultdict(dict)
global_configs = {}
for db_plugin_config in plugin_manager_configs.iterator():
channel = channel_map.get(db_plugin_config.channel_id)
@@ -557,7 +552,7 @@ class PluginsManager(PaymentInterface):
channel_slug=order.channel.slug,
).quantize(Decimal(".0001"))
- def get_tax_rate_type_choices(self) -> List[TaxType]:
+ def get_tax_rate_type_choices(self) -> list[TaxType]:
default_value: list = []
return self.__run_method_on_plugins("get_tax_rate_type_choices", default_value)
@@ -650,7 +645,7 @@ class PluginsManager(PaymentInterface):
"product_updated", default_value, product, webhooks=webhooks
)
- def product_deleted(self, product: "Product", variants: List[int], webhooks=None):
+ def product_deleted(self, product: "Product", variants: list[int], webhooks=None):
default_value = None
return self.__run_method_on_plugins(
"product_deleted", default_value, product, variants, webhooks=webhooks
@@ -933,7 +928,7 @@ class PluginsManager(PaymentInterface):
"order_metadata_updated", default_value, order
)
- def order_bulk_created(self, orders: List["Order"]):
+ def order_bulk_created(self, orders: list["Order"]):
default_value = None
return self.__run_method_on_plugins("order_bulk_created", default_value, orders)
@@ -1626,7 +1621,7 @@ class PluginsManager(PaymentInterface):
gateway: str,
customer_id: str,
channel_slug: str,
- ) -> List["CustomerSource"]:
+ ) -> list["CustomerSource"]:
default_value: list = []
gtw = self.get_plugin(gateway, channel_slug=channel_slug)
if gtw is not None:
@@ -1725,7 +1720,7 @@ class PluginsManager(PaymentInterface):
def get_plugins(
self, channel_slug: Optional[str] = None, active_only=False
- ) -> List["BasePlugin"]:
+ ) -> list["BasePlugin"]:
"""Return list of plugins for a given channel."""
if channel_slug:
plugins = self.plugins_per_channel[channel_slug]
@@ -1743,7 +1738,7 @@ class PluginsManager(PaymentInterface):
checkout_lines: Optional[Iterable["CheckoutLineInfo"]] = None,
channel_slug: Optional[str] = None,
active_only: bool = True,
- ) -> List["PaymentGateway"]:
+ ) -> list["PaymentGateway"]:
channel_slug = checkout_info.channel.slug if checkout_info else channel_slug
plugins = self.get_plugins(channel_slug=channel_slug, active_only=active_only)
payment_plugins = [
@@ -1768,7 +1763,7 @@ class PluginsManager(PaymentInterface):
checkout: "Checkout",
channel_slug: Optional[str] = None,
active_only: bool = True,
- ) -> List["ShippingMethodData"]:
+ ) -> list["ShippingMethodData"]:
channel_slug = channel_slug if channel_slug else checkout.channel.slug
plugins = self.get_plugins(channel_slug=channel_slug, active_only=active_only)
shipping_plugins = [
@@ -1801,7 +1796,7 @@ class PluginsManager(PaymentInterface):
return methods.get(shipping_method_id)
return None
- def list_external_authentications(self, active_only: bool = True) -> List[dict]:
+ def list_external_authentications(self, active_only: bool = True) -> list[dict]:
auth_basic_method = "external_obtain_access_tokens"
plugins = self.get_plugins(active_only=active_only)
return [
@@ -1857,8 +1852,8 @@ class PluginsManager(PaymentInterface):
plugin_configurations = PluginConfiguration.objects.prefetch_related(
"channel"
).all()
- self._plugin_configs_per_channel: DefaultDict[
- Channel, Dict
+ self._plugin_configs_per_channel: defaultdict[
+ Channel, dict
] = defaultdict(dict)
self._global_plugin_configs = {}
for pc in plugin_configurations:
@@ -2030,7 +2025,7 @@ class PluginsManager(PaymentInterface):
self, plugin_id: str, data: dict, request: SaleorContext
) -> dict:
"""Logout the user."""
- default_value: Dict[str, str] = {}
+ default_value: dict[str, str] = {}
plugin = self.get_plugin(plugin_id)
return self.__run_method_on_single_plugin(
plugin, "external_logout", default_value, data, request
@@ -2038,9 +2033,9 @@ class PluginsManager(PaymentInterface):
def external_verify(
self, plugin_id: str, data: dict, request: SaleorContext
- ) -> Tuple[Optional["User"], dict]:
+ ) -> tuple[Optional["User"], dict]:
"""Verify the provided authentication data."""
- default_data: Dict[str, str] = dict()
+ default_data: dict[str, str] = dict()
default_user: Optional["User"] = None
default_value = default_user, default_data
plugin = self.get_plugin(plugin_id)
@@ -2051,8 +2046,8 @@ class PluginsManager(PaymentInterface):
def excluded_shipping_methods_for_order(
self,
order: "Order",
- available_shipping_methods: List["ShippingMethodData"],
- ) -> List[ExcludedShippingMethod]:
+ available_shipping_methods: list["ShippingMethodData"],
+ ) -> list[ExcludedShippingMethod]:
return self.__run_method_on_plugins(
"excluded_shipping_methods_for_order",
[],
@@ -2064,8 +2059,8 @@ class PluginsManager(PaymentInterface):
def excluded_shipping_methods_for_checkout(
self,
checkout: "Checkout",
- available_shipping_methods: List["ShippingMethodData"],
- ) -> List[ExcludedShippingMethod]:
+ available_shipping_methods: list["ShippingMethodData"],
+ ) -> list[ExcludedShippingMethod]:
return self.__run_method_on_plugins(
"excluded_shipping_methods_for_checkout",
[],
diff --git a/saleor/plugins/openid_connect/plugin.py b/saleor/plugins/openid_connect/plugin.py
index 9c5259d787..bc5151ea4e 100644
--- a/saleor/plugins/openid_connect/plugin.py
+++ b/saleor/plugins/openid_connect/plugin.py
@@ -1,5 +1,5 @@
import logging
-from typing import Optional, Tuple
+from typing import Optional
from authlib.common.errors import AuthlibBaseError
from django.core import signing
@@ -451,7 +451,7 @@ class OpenIDConnectPlugin(BasePlugin):
def external_verify(
self, data: dict, request: WSGIRequest, previous_value
- ) -> Tuple[Optional[User], dict]:
+ ) -> tuple[Optional[User], dict]:
if not self.active:
return previous_value
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 5872626287..feb763b2eb 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -1,7 +1,7 @@
import json
import logging
from datetime import datetime
-from typing import TYPE_CHECKING, List, Optional
+from typing import TYPE_CHECKING, Optional
import requests
from authlib.jose import JWTClaims, jwt
@@ -163,7 +163,7 @@ def get_user_from_oauth_access_token_in_jwt_format(
access_token: str,
use_scope_permissions: bool,
audience: str,
- staff_user_domains: List[str],
+ staff_user_domains: list[str],
staff_default_group_name: str,
):
try:
@@ -250,7 +250,7 @@ def get_user_from_oauth_access_token(
user_info_url: str,
use_scope_permissions: bool,
audience: str,
- staff_user_domains: List[str],
+ staff_user_domains: list[str],
staff_default_group_name: str,
):
# we try to decode token to define if the structure is a jwt format.
@@ -315,7 +315,7 @@ def create_jwt_token(
id_payload: CodeIDToken,
user: User,
access_token: str,
- permissions: Optional[List[str]],
+ permissions: Optional[list[str]],
owner: str,
) -> str:
additional_payload = {
@@ -529,7 +529,7 @@ def create_tokens_from_oauth_payload(
token_data: dict,
user: User,
claims: CodeIDToken,
- permissions: Optional[List[str]],
+ permissions: Optional[list[str]],
owner: str,
):
refresh_token = token_data.get("refresh_token")
@@ -601,7 +601,7 @@ def validate_refresh_token(refresh_token, data):
)
-def get_incorrect_or_missing_urls(urls: dict) -> List[str]:
+def get_incorrect_or_missing_urls(urls: dict) -> list[str]:
validator = URLValidator()
incorrect_urls = []
for field, url in urls.items():
@@ -674,6 +674,6 @@ def get_saleor_permissions_from_list(permissions: list) -> QuerySet[Permission]:
return permissions
-def get_saleor_permission_names(permissions: QuerySet) -> List[str]:
+def get_saleor_permission_names(permissions: QuerySet) -> list[str]:
permission_names = get_permission_names(permissions)
return list(permission_names)
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index c4d6d047a1..f0ea461ec3 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -1,12 +1,10 @@
+from collections import defaultdict
+from collections.abc import Iterable
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
- DefaultDict,
- Iterable,
Optional,
- Set,
- Tuple,
Union,
)
@@ -204,7 +202,7 @@ class PluginSample(BasePlugin):
def external_verify(
self, data: dict, request: WSGIRequest, previous_value
- ) -> Tuple[Optional[User], dict]:
+ ) -> tuple[Optional[User], dict]:
user = User.objects.get()
return user, {"some_data": "data"}
@@ -219,7 +217,7 @@ class PluginSample(BasePlugin):
def sale_created(
self,
sale: "Promotion",
- current_catalogue: DefaultDict[str, Set[str]],
+ current_catalogue: defaultdict[str, set[str]],
previous_value: Any,
):
return sale, current_catalogue
@@ -227,8 +225,8 @@ class PluginSample(BasePlugin):
def sale_updated(
self,
sale: "Promotion",
- previous_catalogue: DefaultDict[str, Set[str]],
- current_catalogue: DefaultDict[str, Set[str]],
+ previous_catalogue: defaultdict[str, set[str]],
+ current_catalogue: defaultdict[str, set[str]],
previous_value: Any,
):
return sale, previous_catalogue, current_catalogue
@@ -236,7 +234,7 @@ class PluginSample(BasePlugin):
def sale_deleted(
self,
sale: "Promotion",
- previous_catalogue: DefaultDict[str, Set[str]],
+ previous_catalogue: defaultdict[str, set[str]],
previous_value: Any,
):
return sale, previous_catalogue
@@ -244,7 +242,7 @@ class PluginSample(BasePlugin):
def sale_toggle(
self,
sale: "Promotion",
- catalogue: DefaultDict[str, Set[str]],
+ catalogue: defaultdict[str, set[str]],
previous_value: Any,
):
return sale, catalogue
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 6fe1eb397b..b71fc1972b 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -2,11 +2,11 @@ import json
from decimal import Decimal
from functools import partial
from unittest import mock
+from unittest.mock import patch
import pytest
from django.http import HttpResponseNotFound, JsonResponse
from django.test import override_settings
-from mock import patch
from prices import Money, TaxedMoney
from ...channel import TransactionFlowStrategy
diff --git a/saleor/plugins/tests/utils.py b/saleor/plugins/tests/utils.py
index f7c8149328..340627bb66 100644
--- a/saleor/plugins/tests/utils.py
+++ b/saleor/plugins/tests/utils.py
@@ -1,8 +1,8 @@
-from typing import Dict, List, Union
+from typing import Union
def get_config_value(
- field_name: str, configuration: List[Dict[str, Union[str, bool]]]
+ field_name: str, configuration: list[dict[str, Union[str, bool]]]
) -> Union[str, bool, None]:
for elem in configuration:
if elem["name"] == field_name:
diff --git a/saleor/plugins/user_email/plugin.py b/saleor/plugins/user_email/plugin.py
index bb09ed2667..024c333604 100644
--- a/saleor/plugins/user_email/plugin.py
+++ b/saleor/plugins/user_email/plugin.py
@@ -1,6 +1,6 @@
import logging
from dataclasses import asdict
-from typing import TYPE_CHECKING, List, Union
+from typing import TYPE_CHECKING, Union
from promise.promise import Promise
@@ -362,7 +362,7 @@ class UserEmailPlugin(BasePlugin):
return self.configuration
def map_templates_to_configuration(
- email_templates: List["EmailTemplate"],
+ email_templates: list["EmailTemplate"],
) -> PluginConfigurationType:
email_template_by_name = {
email_template.name: email_template
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 01229cfe36..cf421b5f0a 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1,16 +1,14 @@
import json
import logging
+from collections import defaultdict
+from collections.abc import Iterable
from decimal import Decimal
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
- DefaultDict,
Final,
- Iterable,
- List,
Optional,
- Set,
Union,
)
@@ -902,7 +900,7 @@ class WebhookPlugin(BasePlugin):
def sale_created(
self,
sale: "Promotion",
- current_catalogue: DefaultDict[str, Set[str]],
+ current_catalogue: defaultdict[str, set[str]],
previous_value: Any,
) -> Any:
if not self.active:
@@ -928,8 +926,8 @@ class WebhookPlugin(BasePlugin):
def sale_updated(
self,
sale: "Promotion",
- previous_catalogue: DefaultDict[str, Set[str]],
- current_catalogue: DefaultDict[str, Set[str]],
+ previous_catalogue: defaultdict[str, set[str]],
+ current_catalogue: defaultdict[str, set[str]],
previous_value: Any,
) -> Any:
if not self.active:
@@ -955,7 +953,7 @@ class WebhookPlugin(BasePlugin):
def sale_deleted(
self,
sale: "Promotion",
- previous_catalogue: DefaultDict[str, Set[str]],
+ previous_catalogue: defaultdict[str, set[str]],
previous_value: Any,
webhooks=None,
) -> Any:
@@ -981,7 +979,7 @@ class WebhookPlugin(BasePlugin):
def sale_toggle(
self,
sale: "Promotion",
- catalogue: DefaultDict[str, Set[str]],
+ catalogue: defaultdict[str, set[str]],
previous_value: Any,
):
if not self.active:
@@ -1215,7 +1213,7 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.ORDER_METADATA_UPDATED, order
)
- def order_bulk_created(self, orders: List["Order"], previous_value: Any) -> Any:
+ def order_bulk_created(self, orders: list["Order"], previous_value: Any) -> Any:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.ORDER_BULK_CREATED
@@ -1555,7 +1553,7 @@ class WebhookPlugin(BasePlugin):
def product_deleted(
self,
product: "Product",
- variants: List[int],
+ variants: list[int],
previous_value: Any,
webhooks=None,
) -> Any:
@@ -2730,7 +2728,7 @@ class WebhookPlugin(BasePlugin):
checkout_lines: Optional[Iterable["CheckoutLineInfo"]],
previous_value,
**kwargs,
- ) -> List["PaymentGateway"]:
+ ) -> list["PaymentGateway"]:
gateways = []
checkout = None
if checkout_info:
@@ -2882,7 +2880,7 @@ class WebhookPlugin(BasePlugin):
def get_shipping_methods_for_checkout(
self, checkout: "Checkout", previous_value: Any
- ) -> List["ShippingMethodData"]:
+ ) -> list["ShippingMethodData"]:
methods = []
event_type = WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT
webhooks = get_webhooks_for_event(event_type)
@@ -2938,9 +2936,9 @@ class WebhookPlugin(BasePlugin):
def excluded_shipping_methods_for_order(
self,
order: "Order",
- available_shipping_methods: List["ShippingMethodData"],
- previous_value: List[ExcludedShippingMethod],
- ) -> List[ExcludedShippingMethod]:
+ available_shipping_methods: list["ShippingMethodData"],
+ previous_value: list[ExcludedShippingMethod],
+ ) -> list[ExcludedShippingMethod]:
generate_function = generate_excluded_shipping_methods_for_order_payload
payload_fun = lambda: generate_function( # noqa: E731
order,
@@ -2958,9 +2956,9 @@ class WebhookPlugin(BasePlugin):
def excluded_shipping_methods_for_checkout(
self,
checkout: "Checkout",
- available_shipping_methods: List["ShippingMethodData"],
- previous_value: List[ExcludedShippingMethod],
- ) -> List[ExcludedShippingMethod]:
+ available_shipping_methods: list["ShippingMethodData"],
+ previous_value: list[ExcludedShippingMethod],
+ ) -> list[ExcludedShippingMethod]:
generate_function = generate_excluded_shipping_methods_for_checkout_payload
payload_function = lambda: generate_function( # noqa: E731
checkout,
diff --git a/saleor/plugins/webhook/tests/conftest.py b/saleor/plugins/webhook/tests/conftest.py
index 5200b1302d..8a4600fcae 100644
--- a/saleor/plugins/webhook/tests/conftest.py
+++ b/saleor/plugins/webhook/tests/conftest.py
@@ -1,6 +1,5 @@
import uuid
from decimal import Decimal
-from typing import List
import pytest
from measurement.measures import Weight
@@ -26,7 +25,7 @@ def webhook_plugin(settings):
@pytest.fixture()
def available_shipping_methods_factory():
- def factory(num_methods=1) -> List[ShippingMethodData]:
+ def factory(num_methods=1) -> list[ShippingMethodData]:
methods = []
for i in range(num_methods):
methods.append(
diff --git a/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
index 12a940e39f..f9ee6f5611 100644
--- a/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
+++ b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
@@ -1,5 +1,6 @@
+from unittest import mock
+
import graphene
-import mock
from ....core.models import EventDelivery
from ....payment.interface import ListStoredPaymentMethodsRequestData
diff --git a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
index beacb7dc9a..014dc69bbb 100644
--- a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
+++ b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
@@ -1,7 +1,7 @@
import json
+from unittest import mock
import graphene
-import mock
import pytest
from ....core.models import EventDelivery
diff --git a/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py b/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
index 49c33ea907..129c83f02b 100644
--- a/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
+++ b/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
@@ -1,7 +1,7 @@
import json
+from unittest import mock
import graphene
-import mock
import pytest
from ....core.models import EventDelivery
diff --git a/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py b/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
index b7b0687657..ad45a6ff27 100644
--- a/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
+++ b/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
@@ -1,7 +1,7 @@
import json
+from unittest import mock
import graphene
-import mock
import pytest
from ....core.models import EventDelivery
diff --git a/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py b/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
index cbdc43e87a..d54990a394 100644
--- a/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
+++ b/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
@@ -1,7 +1,7 @@
import json
+from unittest import mock
import graphene
-import mock
import pytest
from ....core.models import EventDelivery
diff --git a/saleor/product/migrations/0003_auto_20150820_1955.py b/saleor/product/migrations/0003_auto_20150820_1955.py
index cce27f9a5a..22879eabd0 100644
--- a/saleor/product/migrations/0003_auto_20150820_1955.py
+++ b/saleor/product/migrations/0003_auto_20150820_1955.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations, models
diff --git a/saleor/product/migrations/0011_stock_quantity_allocated.py b/saleor/product/migrations/0011_stock_quantity_allocated.py
index 2b7e4966e5..37220506c2 100644
--- a/saleor/product/migrations/0011_stock_quantity_allocated.py
+++ b/saleor/product/migrations/0011_stock_quantity_allocated.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.2 on 2016-02-08 14:45
-from __future__ import unicode_literals
from decimal import Decimal
diff --git a/saleor/product/migrations/0012_auto_20160218_0812.py b/saleor/product/migrations/0012_auto_20160218_0812.py
index a7fe28db9b..b28e0679b6 100644
--- a/saleor/product/migrations/0012_auto_20160218_0812.py
+++ b/saleor/product/migrations/0012_auto_20160218_0812.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-02-18 14:12
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/product/migrations/0013_auto_20161130_0608.py b/saleor/product/migrations/0013_auto_20161130_0608.py
index af076da000..05e4e32c3a 100644
--- a/saleor/product/migrations/0013_auto_20161130_0608.py
+++ b/saleor/product/migrations/0013_auto_20161130_0608.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-11-30 12:08
-from __future__ import unicode_literals
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
diff --git a/saleor/product/migrations/0013_auto_20161207_0555.py b/saleor/product/migrations/0013_auto_20161207_0555.py
index 4846bafeb8..97d761bb2a 100644
--- a/saleor/product/migrations/0013_auto_20161207_0555.py
+++ b/saleor/product/migrations/0013_auto_20161207_0555.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-07 11:55
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/product/migrations/0014_auto_20161207_0840.py b/saleor/product/migrations/0014_auto_20161207_0840.py
index 9d8f9a0441..8a6ace278e 100644
--- a/saleor/product/migrations/0014_auto_20161207_0840.py
+++ b/saleor/product/migrations/0014_auto_20161207_0840.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-07 14:40
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0014_remove_productvariant_attributes.py b/saleor/product/migrations/0014_remove_productvariant_attributes.py
index 7e6dea53d9..f6fc98b4be 100644
--- a/saleor/product/migrations/0014_remove_productvariant_attributes.py
+++ b/saleor/product/migrations/0014_remove_productvariant_attributes.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-11-30 12:22
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0015_productvariant_attributes.py b/saleor/product/migrations/0015_productvariant_attributes.py
index f58203b5c3..ae2b62f4f0 100644
--- a/saleor/product/migrations/0015_productvariant_attributes.py
+++ b/saleor/product/migrations/0015_productvariant_attributes.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-11-30 12:26
-from __future__ import unicode_literals
import django.contrib.postgres.fields.hstore
from django.db import migrations
diff --git a/saleor/product/migrations/0015_transfer_locations.py b/saleor/product/migrations/0015_transfer_locations.py
index 6590a635d6..16f699da74 100644
--- a/saleor/product/migrations/0015_transfer_locations.py
+++ b/saleor/product/migrations/0015_transfer_locations.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-07 14:41
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0016_auto_20161204_0311.py b/saleor/product/migrations/0016_auto_20161204_0311.py
index 5d56a0369d..edf712bb85 100644
--- a/saleor/product/migrations/0016_auto_20161204_0311.py
+++ b/saleor/product/migrations/0016_auto_20161204_0311.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-04 09:11
-from __future__ import unicode_literals
import django.contrib.postgres.fields.hstore
from django.db import migrations
diff --git a/saleor/product/migrations/0016_auto_20161207_0843.py b/saleor/product/migrations/0016_auto_20161207_0843.py
index cb80b0ff30..dd92df99cf 100644
--- a/saleor/product/migrations/0016_auto_20161207_0843.py
+++ b/saleor/product/migrations/0016_auto_20161207_0843.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-07 14:43
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0017_attributechoicevalue_slug.py b/saleor/product/migrations/0017_attributechoicevalue_slug.py
index 787beb31ed..d3382202c3 100644
--- a/saleor/product/migrations/0017_attributechoicevalue_slug.py
+++ b/saleor/product/migrations/0017_attributechoicevalue_slug.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-12 13:24
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0017_remove_stock_location.py b/saleor/product/migrations/0017_remove_stock_location.py
index 5e1371545d..88d63936cf 100644
--- a/saleor/product/migrations/0017_remove_stock_location.py
+++ b/saleor/product/migrations/0017_remove_stock_location.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-07 14:43
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0018_auto_20161207_0844.py b/saleor/product/migrations/0018_auto_20161207_0844.py
index 6bf9317f0e..6321aaff5c 100644
--- a/saleor/product/migrations/0018_auto_20161207_0844.py
+++ b/saleor/product/migrations/0018_auto_20161207_0844.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-07 14:44
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0018_auto_20161212_0725.py b/saleor/product/migrations/0018_auto_20161212_0725.py
index e7b9805b97..44bd4723d0 100644
--- a/saleor/product/migrations/0018_auto_20161212_0725.py
+++ b/saleor/product/migrations/0018_auto_20161212_0725.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-12 13:25
-from __future__ import unicode_literals
from django.db import migrations
from django.utils.text import slugify
diff --git a/saleor/product/migrations/0019_auto_20161212_0230.py b/saleor/product/migrations/0019_auto_20161212_0230.py
index 280a51bcda..3a0dffdc0b 100644
--- a/saleor/product/migrations/0019_auto_20161212_0230.py
+++ b/saleor/product/migrations/0019_auto_20161212_0230.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-12 08:30
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/product/migrations/0020_attribute_data_to_class.py b/saleor/product/migrations/0020_attribute_data_to_class.py
index 855e98ecbe..303fbdebc3 100644
--- a/saleor/product/migrations/0020_attribute_data_to_class.py
+++ b/saleor/product/migrations/0020_attribute_data_to_class.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.db import migrations
diff --git a/saleor/product/migrations/0021_add_hstore_extension.py b/saleor/product/migrations/0021_add_hstore_extension.py
index 5d1a46c84e..ccd4384cc3 100644
--- a/saleor/product/migrations/0021_add_hstore_extension.py
+++ b/saleor/product/migrations/0021_add_hstore_extension.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
diff --git a/saleor/product/migrations/0022_auto_20161212_0301.py b/saleor/product/migrations/0022_auto_20161212_0301.py
index 09029e1f34..a450913c31 100644
--- a/saleor/product/migrations/0022_auto_20161212_0301.py
+++ b/saleor/product/migrations/0022_auto_20161212_0301.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-12 09:01
-from __future__ import unicode_literals
import django.contrib.postgres.fields.hstore
import django.db.models.deletion
diff --git a/saleor/product/migrations/0023_auto_20161211_1912.py b/saleor/product/migrations/0023_auto_20161211_1912.py
index be1f2a7079..1c6f581249 100644
--- a/saleor/product/migrations/0023_auto_20161211_1912.py
+++ b/saleor/product/migrations/0023_auto_20161211_1912.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-12 01:12
-from __future__ import unicode_literals
import django.contrib.postgres.fields.hstore
from django.db import migrations
diff --git a/saleor/product/migrations/0024_migrate_json_data.py b/saleor/product/migrations/0024_migrate_json_data.py
index 80fa045864..5cec05d94d 100644
--- a/saleor/product/migrations/0024_migrate_json_data.py
+++ b/saleor/product/migrations/0024_migrate_json_data.py
@@ -1,5 +1,3 @@
-from __future__ import unicode_literals
-
import json
from django.db import migrations
diff --git a/saleor/product/migrations/0025_auto_20161219_0517.py b/saleor/product/migrations/0025_auto_20161219_0517.py
index 382351ff36..c84c44c2a5 100644
--- a/saleor/product/migrations/0025_auto_20161219_0517.py
+++ b/saleor/product/migrations/0025_auto_20161219_0517.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-19 11:17
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0026_merge_20161221_0845.py b/saleor/product/migrations/0026_merge_20161221_0845.py
index 4119c0395e..a2916bd5bc 100644
--- a/saleor/product/migrations/0026_merge_20161221_0845.py
+++ b/saleor/product/migrations/0026_merge_20161221_0845.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2016-12-21 14:45
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0027_auto_20170113_0435.py b/saleor/product/migrations/0027_auto_20170113_0435.py
index 047823ccbd..b9c22e5b58 100644
--- a/saleor/product/migrations/0027_auto_20170113_0435.py
+++ b/saleor/product/migrations/0027_auto_20170113_0435.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2017-01-13 10:35
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0028_merge_20170116_1016.py b/saleor/product/migrations/0028_merge_20170116_1016.py
index f664202b21..2b11294f88 100644
--- a/saleor/product/migrations/0028_merge_20170116_1016.py
+++ b/saleor/product/migrations/0028_merge_20170116_1016.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2017-01-16 16:16
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0029_product_is_featured.py b/saleor/product/migrations/0029_product_is_featured.py
index 37a2579aae..84ca3b28c6 100644
--- a/saleor/product/migrations/0029_product_is_featured.py
+++ b/saleor/product/migrations/0029_product_is_featured.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-01-30 10:12
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0030_auto_20170206_0407.py b/saleor/product/migrations/0030_auto_20170206_0407.py
index 33eac8296e..538bfff5c5 100644
--- a/saleor/product/migrations/0030_auto_20170206_0407.py
+++ b/saleor/product/migrations/0030_auto_20170206_0407.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-06 10:07
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/product/migrations/0031_auto_20170206_0601.py b/saleor/product/migrations/0031_auto_20170206_0601.py
index 465f5aec4d..e76104c6f4 100644
--- a/saleor/product/migrations/0031_auto_20170206_0601.py
+++ b/saleor/product/migrations/0031_auto_20170206_0601.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-06 12:01
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0032_auto_20170216_0438.py b/saleor/product/migrations/0032_auto_20170216_0438.py
index 9e8aae2b2c..c917591c12 100644
--- a/saleor/product/migrations/0032_auto_20170216_0438.py
+++ b/saleor/product/migrations/0032_auto_20170216_0438.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-16 10:38
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0033_auto_20170227_0757.py b/saleor/product/migrations/0033_auto_20170227_0757.py
index 9e9aae7512..d189f08f62 100644
--- a/saleor/product/migrations/0033_auto_20170227_0757.py
+++ b/saleor/product/migrations/0033_auto_20170227_0757.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-27 13:57
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0034_product_is_published.py b/saleor/product/migrations/0034_product_is_published.py
index b2dd1ad94d..944b1def35 100644
--- a/saleor/product/migrations/0034_product_is_published.py
+++ b/saleor/product/migrations/0034_product_is_published.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.6 on 2017-04-05 09:08
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0035_auto_20170919_0846.py b/saleor/product/migrations/0035_auto_20170919_0846.py
index 5fb76f92f9..dc6c8720a5 100644
--- a/saleor/product/migrations/0035_auto_20170919_0846.py
+++ b/saleor/product/migrations/0035_auto_20170919_0846.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-19 13:46
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0036_auto_20171115_0608.py b/saleor/product/migrations/0036_auto_20171115_0608.py
index 6bacf205d1..9e7a5c7649 100644
--- a/saleor/product/migrations/0036_auto_20171115_0608.py
+++ b/saleor/product/migrations/0036_auto_20171115_0608.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-15 12:08
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0037_auto_20171124_0847.py b/saleor/product/migrations/0037_auto_20171124_0847.py
index 66ff45ac73..f1d07d6231 100644
--- a/saleor/product/migrations/0037_auto_20171124_0847.py
+++ b/saleor/product/migrations/0037_auto_20171124_0847.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-24 14:47
-from __future__ import unicode_literals
from django.contrib.postgres.operations import TrigramExtension
from django.db import migrations
diff --git a/saleor/product/migrations/0038_auto_20171129_0616.py b/saleor/product/migrations/0038_auto_20171129_0616.py
index 934b0ea05e..f988c8332c 100644
--- a/saleor/product/migrations/0038_auto_20171129_0616.py
+++ b/saleor/product/migrations/0038_auto_20171129_0616.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-29 12:16
-from __future__ import unicode_literals
from django.contrib.postgres.operations import BtreeGinExtension
from django.db import migrations
diff --git a/saleor/product/migrations/0039_merge_20171130_0727.py b/saleor/product/migrations/0039_merge_20171130_0727.py
index 0e36f81ef0..4498788d12 100644
--- a/saleor/product/migrations/0039_merge_20171130_0727.py
+++ b/saleor/product/migrations/0039_merge_20171130_0727.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-30 13:27
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0040_auto_20171205_0428.py b/saleor/product/migrations/0040_auto_20171205_0428.py
index d18930070a..d1244c2e43 100644
--- a/saleor/product/migrations/0040_auto_20171205_0428.py
+++ b/saleor/product/migrations/0040_auto_20171205_0428.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-12-05 10:28
-from __future__ import unicode_literals
import django.contrib.postgres.indexes
from django.db import migrations
diff --git a/saleor/product/migrations/0042_auto_20171206_0501.py b/saleor/product/migrations/0042_auto_20171206_0501.py
index 12bc6cf914..414dcc9442 100644
--- a/saleor/product/migrations/0042_auto_20171206_0501.py
+++ b/saleor/product/migrations/0042_auto_20171206_0501.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-12-06 11:01
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0043_auto_20171207_0839.py b/saleor/product/migrations/0043_auto_20171207_0839.py
index f7f3abb63d..b7acd1750c 100644
--- a/saleor/product/migrations/0043_auto_20171207_0839.py
+++ b/saleor/product/migrations/0043_auto_20171207_0839.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-12-07 14:39
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/migrations/0044_auto_20180108_0814.py b/saleor/product/migrations/0044_auto_20180108_0814.py
index ca737adde5..7cc909f60e 100644
--- a/saleor/product/migrations/0044_auto_20180108_0814.py
+++ b/saleor/product/migrations/0044_auto_20180108_0814.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-08 14:14
-from __future__ import unicode_literals
from decimal import Decimal
diff --git a/saleor/product/migrations/0045_md_to_html.py b/saleor/product/migrations/0045_md_to_html.py
index e7a3990968..b120ea6439 100644
--- a/saleor/product/migrations/0045_md_to_html.py
+++ b/saleor/product/migrations/0045_md_to_html.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.9 on 2018-01-15 11:16
-from __future__ import unicode_literals
from django.db import migrations
from markdown import markdown
diff --git a/saleor/product/migrations/0046_product_category.py b/saleor/product/migrations/0046_product_category.py
index d474bcea4f..f8c0cddbd2 100644
--- a/saleor/product/migrations/0046_product_category.py
+++ b/saleor/product/migrations/0046_product_category.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.9 on 2018-01-16 11:56
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/product/migrations/0048_product_class_to_type.py b/saleor/product/migrations/0048_product_class_to_type.py
index 4b9f791c76..5d19a3a407 100644
--- a/saleor/product/migrations/0048_product_class_to_type.py
+++ b/saleor/product/migrations/0048_product_class_to_type.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-15 10:28
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0049_collection.py b/saleor/product/migrations/0049_collection.py
index 33525523bb..4adf43a4d1 100644
--- a/saleor/product/migrations/0049_collection.py
+++ b/saleor/product/migrations/0049_collection.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-24 14:13
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0050_auto_20180131_0746.py b/saleor/product/migrations/0050_auto_20180131_0746.py
index bbeaead9de..8c36c86996 100644
--- a/saleor/product/migrations/0050_auto_20180131_0746.py
+++ b/saleor/product/migrations/0050_auto_20180131_0746.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-31 13:46
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/product/migrations/0051_auto_20180202_1106.py b/saleor/product/migrations/0051_auto_20180202_1106.py
index b4b7c6968c..dad5dc87ca 100644
--- a/saleor/product/migrations/0051_auto_20180202_1106.py
+++ b/saleor/product/migrations/0051_auto_20180202_1106.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11 on 2018-02-02 17:06
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/product/models.py b/saleor/product/models.py
index c0bf57834b..8e4945828d 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -1,6 +1,7 @@
import datetime
+from collections.abc import Iterable
from decimal import Decimal
-from typing import Iterable, Optional
+from typing import Optional
from uuid import uuid4
import graphene
@@ -102,12 +103,7 @@ class CategoryTranslation(SeoModelTranslation):
def __repr__(self) -> str:
class_ = type(self)
- return "%s(pk=%r, name=%r, category_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.category_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, name={self.name!r}, category_pk={self.category_id!r})"
def get_translated_object_id(self):
return "Category", self.category_id
@@ -167,12 +163,7 @@ class ProductType(ModelWithMetadata):
def __repr__(self) -> str:
class_ = type(self)
- return "<%s.%s(pk=%r, name=%r)>" % (
- class_.__module__,
- class_.__name__,
- self.pk,
- self.name,
- )
+ return f"<{class_.__module__}.{class_.__name__}(pk={self.pk!r}, name={self.name!r})>"
class Product(SeoModel, ModelWithMetadata, ModelWithExternalReference):
@@ -251,12 +242,7 @@ class Product(SeoModel, ModelWithMetadata, ModelWithExternalReference):
def __repr__(self) -> str:
class_ = type(self)
- return "<%s.%s(pk=%r, name=%r)>" % (
- class_.__module__,
- class_.__name__,
- self.pk,
- self.name,
- )
+ return f"<{class_.__module__}.{class_.__name__}(pk={self.pk!r}, name={self.name!r})>"
def __str__(self) -> str:
return self.name
@@ -286,12 +272,7 @@ class ProductTranslation(SeoModelTranslation):
def __repr__(self) -> str:
class_ = type(self)
- return "%s(pk=%r, name=%r, product_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.product_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, name={self.name!r}, product_pk={self.product_id!r})"
def get_translated_object_id(self):
return "Product", self.product_id
@@ -462,12 +443,7 @@ class ProductVariantTranslation(Translation):
def __repr__(self):
class_ = type(self)
- return "%s(pk=%r, name=%r, variant_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.product_variant_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, name={self.name!r}, variant_pk={self.product_variant_id!r})"
def __str__(self):
return self.name or str(self.product_variant)
@@ -735,12 +711,7 @@ class CollectionTranslation(SeoModelTranslation):
def __repr__(self):
class_ = type(self)
- return "%s(pk=%r, name=%r, collection_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.collection_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, name={self.name!r}, collection_pk={self.collection_id!r})"
def __str__(self) -> str:
return self.name if self.name else str(self.pk)
diff --git a/saleor/product/search.py b/saleor/product/search.py
index e0720f8832..c5f68923b0 100644
--- a/saleor/product/search.py
+++ b/saleor/product/search.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from django.conf import settings
from django.contrib.postgres.search import SearchQuery, SearchRank
@@ -55,7 +55,7 @@ def update_products_search_vector(products: "QuerySet", use_batches=True):
def prepare_product_search_vector_value(
product: "Product", *, already_prefetched=False
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
if not already_prefetched:
prefetch_related_objects([product], *PRODUCT_FIELDS_TO_PREFETCH)
search_vectors = [
@@ -73,7 +73,7 @@ def prepare_product_search_vector_value(
def generate_variants_search_vector_value(
product: "Product",
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
variants = list(product.variants.all()[: settings.PRODUCT_MAX_INDEXED_VARIANTS])
search_vectors = [
@@ -95,7 +95,7 @@ def generate_variants_search_vector_value(
def generate_attributes_search_vector_value(
assigned_attributes: "QuerySet",
-) -> List[NoValidationSearchVector]:
+) -> list[NoValidationSearchVector]:
"""Prepare `search_vector` value for assigned attributes.
Method should receive assigned attributes with prefetched `values`
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index 04f7aba8a8..a313edbaef 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -1,5 +1,5 @@
import logging
-from typing import Iterable, List
+from collections.abc import Iterable
from uuid import UUID
from celery.utils.log import get_task_logger
@@ -64,7 +64,7 @@ def _update_variants_names(instance: ProductType, saved_attributes: Iterable):
@app.task
-def update_variants_names(product_type_pk: int, saved_attributes_ids: List[int]):
+def update_variants_names(product_type_pk: int, saved_attributes_ids: list[int]):
try:
instance = ProductType.objects.get(pk=product_type_pk)
except ObjectDoesNotExist:
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 80bff848f2..5ab1c404af 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -1,4 +1,5 @@
-from typing import TYPE_CHECKING, Dict, Iterable, List, Union
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Union
from ...core.taxes import TaxedMoney, zero_taxed_money
from ...core.tracing import traced_atomic_transaction
@@ -21,7 +22,7 @@ def calculate_revenue_for_variant(
variant: "ProductVariant",
start_date: Union["date", "datetime"],
order_lines: Iterable["OrderLine"],
- orders_dict: Dict["UUID", "Order"],
+ orders_dict: dict["UUID", "Order"],
currency_code: str,
) -> TaxedMoney:
"""Calculate total revenue generated by a product variant."""
@@ -34,7 +35,7 @@ def calculate_revenue_for_variant(
@traced_atomic_transaction()
-def delete_categories(categories_ids: List[Union[str, int]], manager):
+def delete_categories(categories_ids: list[Union[str, int]], manager):
"""Delete categories and perform all necessary actions.
Set products of deleted categories as unpublished, delete categories
@@ -77,7 +78,7 @@ def collect_categories_tree_products(category: "Category") -> "QuerySet[Product]
return products
-def get_products_ids_without_variants(products_list: List["Product"]) -> List[int]:
+def get_products_ids_without_variants(products_list: list["Product"]) -> list[int]:
"""Return list of product's ids without variants."""
products_ids = [product.id for product in products_list]
products_ids_without_variants = Product.objects.filter(
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index 349d772e5a..c5a3fe4026 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from decimal import Decimal
-from typing import List, Optional
+from typing import Optional
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -51,7 +51,7 @@ def _get_total_discount(
def get_product_price_range(
*,
- variants_channel_listing: List[ProductVariantChannelListing],
+ variants_channel_listing: list[ProductVariantChannelListing],
discounted: bool,
) -> Optional[MoneyRange]:
"""Return the range of product prices based on product variants prices.
@@ -90,7 +90,7 @@ def _calculate_product_price_with_taxes(
def get_product_availability(
*,
product_channel_listing: Optional[ProductChannelListing],
- variants_channel_listing: List[ProductVariantChannelListing],
+ variants_channel_listing: list[ProductVariantChannelListing],
prices_entered_with_tax: bool,
tax_calculation_strategy: str,
tax_rate: Decimal,
diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.py
index 1694b5832d..295063e199 100644
--- a/saleor/product/utils/costs.py
+++ b/saleor/product/utils/costs.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
from prices import MoneyRange
@@ -12,8 +13,8 @@ if TYPE_CHECKING:
@dataclass
class CostsData:
- costs: List["Money"]
- margins: List[float]
+ costs: list["Money"]
+ margins: list[float]
def __post_init__(self):
self.costs = sorted(self.costs)
@@ -24,7 +25,7 @@ def get_product_costs_data(
variant_channel_listings: Iterable[ProductVariantChannelListing],
has_variants: bool,
currency: str,
-) -> Tuple[MoneyRange, Tuple[float, float]]:
+) -> tuple[MoneyRange, tuple[float, float]]:
purchase_costs_range = MoneyRange(
start=zero_money(currency), stop=zero_money(currency)
)
@@ -44,8 +45,8 @@ def get_product_costs_data(
def get_cost_data_from_variant_channel_listing(
variant_channel_listings: Iterable["ProductVariantChannelListing"],
) -> CostsData:
- costs: List[CostsData] = []
- margins: List[float] = []
+ costs: list[CostsData] = []
+ margins: list[float] = []
for variant_channel_listing in variant_channel_listings:
costs_data = get_variant_costs_data(variant_channel_listing)
costs += costs_data.costs
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index 0f2fb13d01..28257d40bf 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from decimal import Decimal
-from typing import Dict, List, Optional, Tuple
+from typing import Optional
from uuid import UUID
from django.db.models import Exists, OuterRef
@@ -23,7 +23,7 @@ from ..models import (
def update_discounted_prices_for_promotion(
- products: ProductsQueryset, rules_info: Optional[List[PromotionRuleInfo]] = None
+ products: ProductsQueryset, rules_info: Optional[list[PromotionRuleInfo]] = None
):
"""Update Products and ProductVariants discounted prices.
@@ -99,12 +99,12 @@ def update_discounted_prices_for_promotion(
def _update_or_create_listings(
- changed_products_listings_to_update: List[ProductChannelListing],
- changed_variants_listings_to_update: List[ProductVariantChannelListing],
- changed_variant_listing_promotion_rule_to_create: List[
+ changed_products_listings_to_update: list[ProductChannelListing],
+ changed_variants_listings_to_update: list[ProductVariantChannelListing],
+ changed_variant_listing_promotion_rule_to_create: list[
VariantChannelListingPromotionRule
],
- changed_variant_listing_promotion_rule_to_update: List[
+ changed_variant_listing_promotion_rule_to_update: list[
VariantChannelListingPromotionRule
],
):
@@ -142,7 +142,7 @@ def _get_product_to_variant_channel_listings_per_channel_map(
).iterator()
}
- price_data: Dict[int, Dict[int, List[Money]]] = defaultdict(
+ price_data: dict[int, dict[int, list[Money]]] = defaultdict(
lambda: defaultdict(list)
)
for variant_channel_listing in variant_channel_listings.iterator():
@@ -165,8 +165,8 @@ def _get_variant_listings_to_listing_rule_per_rule_id_map(
}
}
"""
- variant_listing_rule_data: Dict[
- int, Dict[UUID, VariantChannelListingPromotionRule]
+ variant_listing_rule_data: dict[
+ int, dict[UUID, VariantChannelListingPromotionRule]
] = defaultdict(dict)
variant_channel_listings = ProductVariantChannelListing.objects.filter(
Exists(variants.filter(id=OuterRef("variant_id"))), price_amount__isnull=False
@@ -185,22 +185,22 @@ def _get_variant_listings_to_listing_rule_per_rule_id_map(
def _get_discounted_variants_prices_for_promotions(
- variant_listings: List[ProductVariantChannelListing],
- rules_info_per_promotion_id: Dict[UUID, List[PromotionRuleInfo]],
+ variant_listings: list[ProductVariantChannelListing],
+ rules_info_per_promotion_id: dict[UUID, list[PromotionRuleInfo]],
channel: Channel,
variant_listing_to_listing_rule_per_rule_map: dict,
-) -> Tuple[
+) -> tuple[
Money,
- List[ProductVariantChannelListing],
- List[VariantChannelListingPromotionRule],
- List[VariantChannelListingPromotionRule],
+ list[ProductVariantChannelListing],
+ list[VariantChannelListingPromotionRule],
+ list[VariantChannelListingPromotionRule],
]:
- variants_listings_to_update: List[ProductVariantChannelListing] = []
- discounted_variants_price: List[Money] = []
- variant_listing_promotion_rule_to_create: List[
+ variants_listings_to_update: list[ProductVariantChannelListing] = []
+ discounted_variants_price: list[Money] = []
+ variant_listing_promotion_rule_to_create: list[
VariantChannelListingPromotionRule
] = []
- variant_listing_promotion_rule_to_update: List[
+ variant_listing_promotion_rule_to_update: list[
VariantChannelListingPromotionRule
] = []
for variant_listing in variant_listings:
@@ -257,8 +257,8 @@ def _handle_discount_rule_id(
variant_listing_to_listing_rule_per_rule_map: dict,
discount_amount: Decimal,
currency: str,
- variant_listing_promotion_rule_to_update: List[VariantChannelListingPromotionRule],
- variant_listing_promotion_rule_to_create: List[VariantChannelListingPromotionRule],
+ variant_listing_promotion_rule_to_update: list[VariantChannelListingPromotionRule],
+ variant_listing_promotion_rule_to_create: list[VariantChannelListingPromotionRule],
):
listing_promotion_rule = variant_listing_to_listing_rule_per_rule_map[
variant_listing.id
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index 278105a932..3257043d5b 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -1,4 +1,5 @@
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional
from ...attribute import AttributeType
@@ -33,8 +34,8 @@ def generate_and_set_variant_name(
def get_variant_selection_attributes(
- attributes: Iterable[Tuple["Attribute", bool]]
-) -> List[Tuple["Attribute", bool]]:
+ attributes: Iterable[tuple["Attribute", bool]]
+) -> list[tuple["Attribute", bool]]:
"""Return attributes that can be used in variant selection.
Attribute must be product attribute and attribute input type must be
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 9a421f8534..cc75fcdac6 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -24,14 +24,14 @@ def digital_product(request, token: str) -> Union[FileResponse, HttpResponseNotF
digital_content.content_file.open()
opened_file = digital_content.content_file.file
filename = os.path.basename(digital_content.content_file.name)
- file_expr = 'filename="{}"'.format(filename)
+ file_expr = f'filename="{filename}"'
content_type = mimetypes.guess_type(str(filename))[0]
response = FileResponse(opened_file)
response["Content-Length"] = digital_content.content_file.size
response["Content-Type"] = str(content_type)
- response["Content-Disposition"] = "attachment; {}".format(file_expr)
+ response["Content-Disposition"] = f"attachment; {file_expr}"
increment_download_count(content_url)
return response
diff --git a/saleor/schedulers/models.py b/saleor/schedulers/models.py
index bbc9cee674..d299726e3c 100644
--- a/saleor/schedulers/models.py
+++ b/saleor/schedulers/models.py
@@ -1,5 +1,4 @@
import importlib
-from typing import Dict
from celery.schedules import BaseSchedule
from django.core.exceptions import SuspiciousOperation, ValidationError
@@ -31,7 +30,7 @@ class CustomSchedule(models.Model): # type: ignore[django-manager-missing] # pr
no_changes = False
- CACHED_SCHEDULES: Dict[str, BaseSchedule] = {}
+ CACHED_SCHEDULES: dict[str, BaseSchedule] = {}
schedule_import_path = models.CharField(
max_length=255,
help_text="The python import path where the Celery scheduler is defined at",
diff --git a/saleor/schedulers/schedulers.py b/saleor/schedulers/schedulers.py
index 3bc707fb3e..9b2e5deaa8 100644
--- a/saleor/schedulers/schedulers.py
+++ b/saleor/schedulers/schedulers.py
@@ -1,7 +1,7 @@
import copy
import logging
import time
-from typing import Any, List, NamedTuple, Optional
+from typing import Any, NamedTuple, Optional
import celery.beat
import celery.schedules
@@ -92,7 +92,7 @@ class BaseScheduler(celery.beat.Scheduler):
self.old_schedulers = copy.copy(self.schedule)
self.populate_heap()
- H: Optional[List[HeapEventType]] = self._heap
+ H: Optional[list[HeapEventType]] = self._heap
if not H:
return max_interval
diff --git a/saleor/settings.py b/saleor/settings.py
index 33f5369966..09602f8d9b 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -4,7 +4,7 @@ import os
import os.path
import warnings
from datetime import timedelta
-from typing import List, Optional
+from typing import Optional
from urllib.parse import urlparse
import dj_database_url
@@ -43,7 +43,7 @@ def get_bool_from_env(name, default_value):
try:
return ast.literal_eval(value)
except ValueError as e:
- raise ValueError("{} is an invalid value for {}".format(value, name)) from e
+ raise ValueError(f"{value} is an invalid value for {name}") from e
return default_value
@@ -434,7 +434,7 @@ TEST_RUNNER = "saleor.tests.runner.PytestTestRunner"
PLAYGROUND_ENABLED = get_bool_from_env("PLAYGROUND_ENABLED", True)
ALLOWED_HOSTS = get_list(os.environ.get("ALLOWED_HOSTS", "localhost,127.0.0.1"))
-ALLOWED_GRAPHQL_ORIGINS: List[str] = get_list(
+ALLOWED_GRAPHQL_ORIGINS: list[str] = get_list(
os.environ.get("ALLOWED_GRAPHQL_ORIGINS", "*")
)
@@ -697,7 +697,7 @@ def SENTRY_INIT(dsn: str, sentry_opts: dict):
GRAPHQL_PAGINATION_LIMIT = 100
-GRAPHQL_MIDDLEWARE: List[str] = []
+GRAPHQL_MIDDLEWARE: list[str] = []
# Set GRAPHQL_QUERY_MAX_COMPLEXITY=0 in env to disable (not recommended)
GRAPHQL_QUERY_MAX_COMPLEXITY = int(
@@ -733,7 +733,7 @@ BUILTIN_PLUGINS = [
EXTERNAL_PLUGINS = []
installed_plugins = pkg_resources.iter_entry_points("saleor.plugins")
for entry_point in installed_plugins:
- plugin_path = "{}.{}".format(entry_point.module_name, entry_point.attrs[0])
+ plugin_path = f"{entry_point.module_name}.{entry_point.attrs[0]}"
if plugin_path not in BUILTIN_PLUGINS and plugin_path not in EXTERNAL_PLUGINS:
if entry_point.name not in INSTALLED_APPS:
INSTALLED_APPS.append(entry_point.name)
diff --git a/saleor/shipping/interface.py b/saleor/shipping/interface.py
index c2f3bf1e5a..e51555d73f 100644
--- a/saleor/shipping/interface.py
+++ b/saleor/shipping/interface.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Dict, Optional
+from typing import TYPE_CHECKING, Optional
import graphene
import graphql
@@ -28,8 +28,8 @@ class ShippingMethodData:
maximum_order_weight: Optional[Weight] = None
maximum_delivery_days: Optional[int] = None
minimum_delivery_days: Optional[int] = None
- metadata: Dict[str, str] = field(default_factory=dict)
- private_metadata: Dict[str, str] = field(default_factory=dict)
+ metadata: dict[str, str] = field(default_factory=dict)
+ private_metadata: dict[str, str] = field(default_factory=dict)
tax_class: Optional["TaxClass"] = None
active: bool = True
message: str = ""
diff --git a/saleor/shipping/migrations/0001_initial.py b/saleor/shipping/migrations/0001_initial.py
index 23d1911179..3b5aa89ebc 100644
--- a/saleor/shipping/migrations/0001_initial.py
+++ b/saleor/shipping/migrations/0001_initial.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9.1 on 2016-01-19 10:18
-from __future__ import unicode_literals
import django.db.models.manager
from django.db import migrations, models
diff --git a/saleor/shipping/migrations/0002_auto_20160906_0741.py b/saleor/shipping/migrations/0002_auto_20160906_0741.py
index 6a2c29a44d..b6006db772 100644
--- a/saleor/shipping/migrations/0002_auto_20160906_0741.py
+++ b/saleor/shipping/migrations/0002_auto_20160906_0741.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.1 on 2016-09-06 12:41
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/shipping/migrations/0003_auto_20170116_0700.py b/saleor/shipping/migrations/0003_auto_20170116_0700.py
index 780630d98f..b26e3bcf6d 100644
--- a/saleor/shipping/migrations/0003_auto_20170116_0700.py
+++ b/saleor/shipping/migrations/0003_auto_20170116_0700.py
@@ -1,5 +1,4 @@
# Generated by Django 1.9 on 2017-01-16 13:00
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/shipping/migrations/0004_auto_20170206_0407.py b/saleor/shipping/migrations/0004_auto_20170206_0407.py
index 2082bc49d3..b6b2944942 100644
--- a/saleor/shipping/migrations/0004_auto_20170206_0407.py
+++ b/saleor/shipping/migrations/0004_auto_20170206_0407.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-06 10:07
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/shipping/migrations/0005_auto_20170906_0556.py b/saleor/shipping/migrations/0005_auto_20170906_0556.py
index e415f9a836..517f65e6a5 100644
--- a/saleor/shipping/migrations/0005_auto_20170906_0556.py
+++ b/saleor/shipping/migrations/0005_auto_20170906_0556.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-06 10:56
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/shipping/migrations/0006_auto_20171109_0908.py b/saleor/shipping/migrations/0006_auto_20171109_0908.py
index 8e9ae5c4c7..9cfa0d1650 100644
--- a/saleor/shipping/migrations/0006_auto_20171109_0908.py
+++ b/saleor/shipping/migrations/0006_auto_20171109_0908.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-09 15:08
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/shipping/migrations/0007_auto_20171129_1004.py b/saleor/shipping/migrations/0007_auto_20171129_1004.py
index f080c7be3a..3258cb3788 100644
--- a/saleor/shipping/migrations/0007_auto_20171129_1004.py
+++ b/saleor/shipping/migrations/0007_auto_20171129_1004.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-29 16:04
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/shipping/migrations/0008_auto_20180108_0814.py b/saleor/shipping/migrations/0008_auto_20180108_0814.py
index e9b86e9087..223d478e21 100644
--- a/saleor/shipping/migrations/0008_auto_20180108_0814.py
+++ b/saleor/shipping/migrations/0008_auto_20180108_0814.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-08 14:14
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 26003b8165..a9dec0da8f 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, List, Optional, Union
+from typing import TYPE_CHECKING, Optional, Union
from django.conf import settings
from django.db import models
@@ -70,11 +71,8 @@ def _get_weight_type_display(min_weight, max_weight):
max_weight = convert_weight(max_weight, default_unit)
if max_weight is None:
- return ("%(min_weight)s and up" % {"min_weight": min_weight},)
- return "%(min_weight)s to %(max_weight)s" % {
- "min_weight": min_weight,
- "max_weight": max_weight,
- }
+ return f"{min_weight} and up"
+ return f"{min_weight} to {max_weight}"
class ShippingZone(ModelWithMetadata):
@@ -116,7 +114,7 @@ class ShippingMethodQueryset(models.QuerySet["ShippingMethod"]):
)
def exclude_shipping_methods_for_excluded_products(
- self, qs, product_ids: List[int]
+ self, qs, product_ids: list[int]
):
"""Exclude the ShippingMethods which have excluded given products."""
return qs.exclude(excluded_products__id__in=product_ids)
diff --git a/saleor/shipping/postal_codes.py b/saleor/shipping/postal_codes.py
index c19aca2ccd..dffdcebb05 100644
--- a/saleor/shipping/postal_codes.py
+++ b/saleor/shipping/postal_codes.py
@@ -1,11 +1,11 @@
import re
-from typing import Any, List, Optional, Tuple
+from typing import Any, Optional
from . import PostalCodeRuleInclusionType
def group_values(pattern, *values):
- result: List[Optional[Tuple[Any, ...]]] = []
+ result: list[Optional[tuple[Any, ...]]] = []
for value in values:
try:
val = re.match(pattern, value)
diff --git a/saleor/shipping/tasks.py b/saleor/shipping/tasks.py
index b534a524f9..6c4a7dcbb0 100644
--- a/saleor/shipping/tasks.py
+++ b/saleor/shipping/tasks.py
@@ -1,4 +1,5 @@
-from typing import Iterable, Union
+from collections.abc import Iterable
+from typing import Union
from django.utils import timezone
diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.py
index fa462c140a..7a07c3beb9 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -1,5 +1,5 @@
import logging
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING
from django_countries import countries
@@ -55,8 +55,8 @@ def convert_to_shipping_method_data(
def initialize_shipping_method_active_status(
- shipping_methods: List["ShippingMethodData"],
- excluded_methods: List["ExcludedShippingMethod"],
+ shipping_methods: list["ShippingMethodData"],
+ excluded_methods: list["ExcludedShippingMethod"],
):
reason_map = {str(method.id): method.reason for method in excluded_methods}
for instance in shipping_methods:
diff --git a/saleor/site/migrations/0001_initial.py b/saleor/site/migrations/0001_initial.py
index 516cdb0d4c..c5ba651f3b 100644
--- a/saleor/site/migrations/0001_initial.py
+++ b/saleor/site/migrations/0001_initial.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.3 on 2017-01-13 12:38
-from __future__ import unicode_literals
import django.contrib.sites.models
from django.db import migrations, models
diff --git a/saleor/site/migrations/0002_add_default_data.py b/saleor/site/migrations/0002_add_default_data.py
index 81fb814bfe..d1865d46f3 100644
--- a/saleor/site/migrations/0002_add_default_data.py
+++ b/saleor/site/migrations/0002_add_default_data.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-01-27 11:41
-from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
diff --git a/saleor/site/migrations/0003_sitesettings_description.py b/saleor/site/migrations/0003_sitesettings_description.py
index cb947beb6c..c5787a6ea1 100644
--- a/saleor/site/migrations/0003_sitesettings_description.py
+++ b/saleor/site/migrations/0003_sitesettings_description.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-08 12:42
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/site/migrations/0004_auto_20170221_0426.py b/saleor/site/migrations/0004_auto_20170221_0426.py
index 47708817bf..0bc537ae9b 100644
--- a/saleor/site/migrations/0004_auto_20170221_0426.py
+++ b/saleor/site/migrations/0004_auto_20170221_0426.py
@@ -1,5 +1,4 @@
# Generated by Django 1.10.5 on 2017-02-21 10:26
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/site/migrations/0005_auto_20170906_0556.py b/saleor/site/migrations/0005_auto_20170906_0556.py
index 0fd399fe58..29513bd16f 100644
--- a/saleor/site/migrations/0005_auto_20170906_0556.py
+++ b/saleor/site/migrations/0005_auto_20170906_0556.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.4 on 2017-09-06 10:56
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/site/migrations/0006_auto_20171025_0454.py b/saleor/site/migrations/0006_auto_20171025_0454.py
index fc6c89bdb1..5deee2e869 100644
--- a/saleor/site/migrations/0006_auto_20171025_0454.py
+++ b/saleor/site/migrations/0006_auto_20171025_0454.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-10-25 09:54
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/site/migrations/0007_auto_20171027_0856.py b/saleor/site/migrations/0007_auto_20171027_0856.py
index d5812e9cf8..05d9dbfdb5 100644
--- a/saleor/site/migrations/0007_auto_20171027_0856.py
+++ b/saleor/site/migrations/0007_auto_20171027_0856.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-10-27 13:56
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/site/migrations/0008_auto_20171027_0856.py b/saleor/site/migrations/0008_auto_20171027_0856.py
index acc4423e89..862184a950 100644
--- a/saleor/site/migrations/0008_auto_20171027_0856.py
+++ b/saleor/site/migrations/0008_auto_20171027_0856.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-10-27 13:56
-from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
diff --git a/saleor/site/migrations/0009_auto_20171109_0849.py b/saleor/site/migrations/0009_auto_20171109_0849.py
index ef5a72b499..c97f14b0d6 100644
--- a/saleor/site/migrations/0009_auto_20171109_0849.py
+++ b/saleor/site/migrations/0009_auto_20171109_0849.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-09 14:49
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/site/migrations/0010_auto_20171113_0958.py b/saleor/site/migrations/0010_auto_20171113_0958.py
index 3e8f3fda64..c00905295b 100644
--- a/saleor/site/migrations/0010_auto_20171113_0958.py
+++ b/saleor/site/migrations/0010_auto_20171113_0958.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2017-11-13 15:58
-from __future__ import unicode_literals
from django.db import migrations
diff --git a/saleor/site/migrations/0011_auto_20180108_0814.py b/saleor/site/migrations/0011_auto_20180108_0814.py
index 6fc413c317..2275cd7e99 100644
--- a/saleor/site/migrations/0011_auto_20180108_0814.py
+++ b/saleor/site/migrations/0011_auto_20180108_0814.py
@@ -1,5 +1,4 @@
# Generated by Django 1.11.5 on 2018-01-08 14:14
-from __future__ import unicode_literals
from django.db import migrations, models
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 1e85625407..e34df7691c 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -140,11 +140,7 @@ class SiteSettingsTranslation(Translation):
def __repr__(self):
class_ = type(self)
- return "%s(pk=%r, site_settings_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.site_settings_id,
- )
+ return f"{class_.__name__}(pk={self.pk!r}, site_settings_pk={self.site_settings_id!r})"
def get_translated_object_id(self):
return "Shop", self.site_settings_id
diff --git a/saleor/site/patch_sites.py b/saleor/site/patch_sites.py
index 069dd9c36a..2c208dab34 100644
--- a/saleor/site/patch_sites.py
+++ b/saleor/site/patch_sites.py
@@ -5,7 +5,7 @@ multiple instances of the application server, we're patching it with
a thread-safe structure and methods that use it underneath.
"""
import threading
-from typing import Dict, Union
+from typing import Union
from django.contrib.sites.models import Site, SiteManager
from django.core.exceptions import ImproperlyConfigured
@@ -13,7 +13,7 @@ from django.http.request import split_domain_port
lock = threading.Lock()
with lock:
- THREADED_SITE_CACHE: Dict[Union[str, int], Site] = {}
+ THREADED_SITE_CACHE: dict[Union[str, int], Site] = {}
def new_get_current(self, request=None):
diff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.py
index a674f57ffd..15b80ff83e 100644
--- a/saleor/tax/calculations/checkout.py
+++ b/saleor/tax/calculations/checkout.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, Optional
+from typing import TYPE_CHECKING, Optional
from prices import TaxedMoney
diff --git a/saleor/tax/calculations/order.py b/saleor/tax/calculations/order.py
index 074e8039d8..1050680775 100644
--- a/saleor/tax/calculations/order.py
+++ b/saleor/tax/calculations/order.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, Tuple
+from typing import TYPE_CHECKING
from prices import Money, TaxedMoney
@@ -113,7 +114,7 @@ def update_taxes_for_order_lines(
country_code: str,
default_tax_rate: Decimal,
prices_entered_with_tax: bool,
-) -> Tuple[Iterable["OrderLine"], TaxedMoney]:
+) -> tuple[Iterable["OrderLine"], TaxedMoney]:
currency = order.currency
lines = list(lines)
diff --git a/saleor/tax/migrations/0005_migrate_vatlayer.py b/saleor/tax/migrations/0005_migrate_vatlayer.py
index 5b1a5535a1..f87b50f8af 100644
--- a/saleor/tax/migrations/0005_migrate_vatlayer.py
+++ b/saleor/tax/migrations/0005_migrate_vatlayer.py
@@ -1,6 +1,6 @@
# Generated by Django 3.2.14 on 2022-08-18 10:31
-from typing import List, Optional
+from typing import Optional
from django.db import migrations
from django_countries import countries
@@ -16,7 +16,7 @@ def _clear_country_code(country_code: str) -> Optional[str]:
return countries.alpha2(country_code.strip()) if country_code else None
-def _clear_str_list_country_codes(country_codes: str) -> List[str]:
+def _clear_str_list_country_codes(country_codes: str) -> list[str]:
countries = [_clear_country_code(cc) for cc in country_codes.split(",")]
return [cc for cc in countries if cc]
diff --git a/saleor/tax/utils.py b/saleor/tax/utils.py
index 73644650cb..905998d565 100644
--- a/saleor/tax/utils.py
+++ b/saleor/tax/utils.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
from prices import TaxedMoney
@@ -106,7 +107,7 @@ def get_tax_calculation_strategy_for_order(order: "Order"):
def _get_tax_configuration_for_checkout(
checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]
-) -> Tuple["TaxConfiguration", Optional["TaxConfigurationPerCountry"]]:
+) -> tuple["TaxConfiguration", Optional["TaxConfigurationPerCountry"]]:
tax_configuration = checkout_info.tax_configuration
country_code = get_active_country(
checkout_info.channel,
diff --git a/saleor/tests/dummy_password_hasher.py b/saleor/tests/dummy_password_hasher.py
index 8f06296d77..ceeeb11c58 100644
--- a/saleor/tests/dummy_password_hasher.py
+++ b/saleor/tests/dummy_password_hasher.py
@@ -14,7 +14,7 @@ class DummyHasher(BasePasswordHasher):
def encode(self, password, *args):
assert password is not None
- return "%s$%s" % (self.algorithm, password)
+ return f"{self.algorithm}${password}"
def verify(self, password, encoded):
algorithm, dummy_password = encoded.split("$")
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 9afe003872..4d18be2741 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -7,7 +7,7 @@ from datetime import timedelta
from decimal import Decimal
from functools import partial
from io import BytesIO
-from typing import Callable, List, Optional
+from typing import Callable, Optional
from unittest.mock import MagicMock, Mock
import graphene
@@ -200,7 +200,7 @@ def _assert_num_queries(context, *, config, num, exact=True, info=None):
),
)
if info:
- msg += "\n{}".format(info)
+ msg += f"\n{info}"
if verbose:
sqls = (q["sql"] for q in context.captured_queries)
msg += "\n\nQueries:\n========\n\n%s" % "\n\n".join(sqls)
@@ -2279,7 +2279,7 @@ def page_file_attribute(db):
@pytest.fixture
-def product_type_attribute_list() -> List[Attribute]:
+def product_type_attribute_list() -> list[Attribute]:
return list(
Attribute.objects.bulk_create(
[
@@ -2298,7 +2298,7 @@ def product_type_attribute_list() -> List[Attribute]:
@pytest.fixture
-def page_type_attribute_list() -> List[Attribute]:
+def page_type_attribute_list() -> list[Attribute]:
return list(
Attribute.objects.bulk_create(
[
@@ -6547,13 +6547,13 @@ def transaction_item_generator():
@pytest.fixture
def transaction_events_generator() -> (
Callable[
- [List[str], List[str], List[Decimal], TransactionItem], List[TransactionEvent]
+ [list[str], list[str], list[Decimal], TransactionItem], list[TransactionEvent]
]
):
def factory(
- psp_references: List[str],
- types: List[str],
- amounts: List[Decimal],
+ psp_references: list[str],
+ types: list[str],
+ amounts: list[Decimal],
transaction: TransactionItem,
):
return TransactionEvent.objects.bulk_create(
diff --git a/saleor/tests/runner.py b/saleor/tests/runner.py
index ca8e13b879..aba1d2e025 100644
--- a/saleor/tests/runner.py
+++ b/saleor/tests/runner.py
@@ -1,4 +1,4 @@
-class PytestTestRunner(object):
+class PytestTestRunner:
"""Runs pytest to discover and run tests."""
def __init__(self, verbosity=1, failfast=False, keepdb=True, **kwargs):
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index 21b3cf816d..472149e5e2 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -1,5 +1,6 @@
import re
-from typing import List, Pattern, Union
+from re import Pattern
+from typing import Union
from django.utils.functional import SimpleLazyObject
@@ -46,7 +47,7 @@ PASSWORD_HASHERS = ["saleor.tests.dummy_password_hasher.DummyHasher"]
PLUGINS = []
-PATTERNS_IGNORED_IN_QUERY_CAPTURES: List[Union[Pattern, SimpleLazyObject]] = [
+PATTERNS_IGNORED_IN_QUERY_CAPTURES: list[Union[Pattern, SimpleLazyObject]] = [
lazy_re_compile(r"^SET\s+")
]
diff --git a/saleor/thumbnail/validators.py b/saleor/thumbnail/validators.py
index 4352c9a4df..76c6a7c19e 100644
--- a/saleor/thumbnail/validators.py
+++ b/saleor/thumbnail/validators.py
@@ -1,4 +1,5 @@
-from typing import Collection, Optional
+from collections.abc import Collection
+from typing import Optional
from django.core.exceptions import ValidationError
from PIL import Image, UnidentifiedImageError
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 320afc2594..d48d0e81fd 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -1,14 +1,11 @@
from collections import defaultdict
+from collections.abc import Iterable
from typing import (
TYPE_CHECKING,
Any,
- Dict,
- Iterable,
- List,
NamedTuple,
NoReturn,
Optional,
- Tuple,
)
from django.core.exceptions import ValidationError
@@ -35,15 +32,15 @@ class ChannelListingPreorderAvailbilityInfo(NamedTuple):
class VariantsChannelAvailbilityInfo(NamedTuple):
- variants_channel_availability: Dict[int, ChannelListingPreorderAvailbilityInfo]
- variants_global_allocations: Dict[int, int]
+ variants_channel_availability: dict[int, ChannelListingPreorderAvailbilityInfo]
+ variants_global_allocations: dict[int, int]
all_variants_channel_listings: QuerySet[ProductVariantChannelListing]
- variant_channels: Dict[int, List[ProductVariantChannelListing]]
+ variant_channels: dict[int, list[ProductVariantChannelListing]]
def _get_available_quantity(
stocks: StockQuerySet,
- checkout_lines: Optional[List["CheckoutLine"]] = None,
+ checkout_lines: Optional[list["CheckoutLine"]] = None,
check_reservations: bool = False,
) -> int:
results = stocks.aggregate(
@@ -66,7 +63,7 @@ def check_stock_and_preorder_quantity(
country_code: str,
channel_slug: str,
quantity: int,
- checkout_lines: Optional[List["CheckoutLine"]] = None,
+ checkout_lines: Optional[list["CheckoutLine"]] = None,
check_reservations: bool = False,
):
"""Validate if there is stock/preorder available for given variant.
@@ -94,7 +91,7 @@ def check_stock_quantity(
country_code: str,
channel_slug: str,
quantity: int,
- checkout_lines: Optional[List["CheckoutLine"]] = None,
+ checkout_lines: Optional[list["CheckoutLine"]] = None,
check_reservations: bool = False,
):
"""Validate if there is stock available for given variant in given country.
@@ -127,7 +124,7 @@ def check_stock_and_preorder_quantity_bulk(
channel_slug: str,
global_quantity_limit: Optional[int],
delivery_method_info: Optional["DeliveryMethodBase"] = None,
- additional_filter_lookup: Optional[Dict[str, Any]] = None,
+ additional_filter_lookup: Optional[dict[str, Any]] = None,
existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,
replace: bool = False,
check_reservations: bool = False,
@@ -170,7 +167,7 @@ def check_stock_and_preorder_quantity_bulk(
def _split_lines_for_trackable_and_preorder(
variants: Iterable["ProductVariant"], quantities: Iterable[int]
-) -> Tuple[
+) -> tuple[
Iterable["ProductVariant"], Iterable[int], Iterable["ProductVariant"], Iterable[int]
]:
"""Return variants and quantities splitted by "is_preorder_active"."""
@@ -219,7 +216,7 @@ def check_stock_quantity_bulk(
channel_slug: str,
global_quantity_limit: Optional[int],
delivery_method_info: Optional["DeliveryMethodBase"] = None,
- additional_filter_lookup: Optional[Dict[str, Any]] = None,
+ additional_filter_lookup: Optional[dict[str, Any]] = None,
existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,
replace=False,
check_reservations: bool = False,
@@ -253,7 +250,7 @@ def check_stock_quantity_bulk(
all_variants_stocks = stocks.filter(**filter_lookup).annotate_available_quantity()
- variant_stocks: Dict[int, List[Stock]] = defaultdict(list)
+ variant_stocks: dict[int, list[Stock]] = defaultdict(list)
for stock in all_variants_stocks:
variant_stocks[stock.product_variant_id].append(stock)
@@ -265,7 +262,7 @@ def check_stock_quantity_bulk(
else:
variant_reservations = defaultdict(int)
- insufficient_stocks: List[InsufficientStockData] = []
+ insufficient_stocks: list[InsufficientStockData] = []
variants_quantities = {
line.variant.pk: line.line.quantity for line in existing_lines or []
}
@@ -323,7 +320,7 @@ def _get_variants_channel_availbility_info(
if channel_listing.channel.slug == channel_slug
}
- variant_channels: Dict[int, List[ProductVariantChannelListing]] = defaultdict(list)
+ variant_channels: dict[int, list[ProductVariantChannelListing]] = defaultdict(list)
for channel_listing in all_variants_channel_listings:
variant_channels[channel_listing.variant_id].append(channel_listing)
@@ -368,7 +365,7 @@ def check_preorder_threshold_in_orders(
else:
listings_reservations = defaultdict(int)
- insufficient_stocks: List[InsufficientStockData] = []
+ insufficient_stocks: list[InsufficientStockData] = []
if (
variants_channel_availability[variant.id].preorder_quantity_threshold
@@ -436,7 +433,7 @@ def check_preorder_threshold_bulk(
else:
listings_reservations = defaultdict(int)
- insufficient_stocks: List[InsufficientStockData] = []
+ insufficient_stocks: list[InsufficientStockData] = []
variants_quantities = {
line.variant.pk: line.line.quantity for line in existing_lines or []
}
@@ -491,7 +488,7 @@ def get_available_quantity(
variant: "ProductVariant",
country_code: str,
channel_slug: str,
- checkout_lines: Optional[List["CheckoutLine"]] = None,
+ checkout_lines: Optional[list["CheckoutLine"]] = None,
check_reservations: bool = False,
) -> int:
"""Return available quantity for given product in given country."""
@@ -514,7 +511,7 @@ def is_product_in_stock(
def get_reserved_stock_quantity(
- stocks: StockQuerySet, lines: Optional[List["CheckoutLine"]] = None
+ stocks: StockQuerySet, lines: Optional[list["CheckoutLine"]] = None
) -> int:
result = (
Reservation.objects.filter(
@@ -533,8 +530,8 @@ def get_reserved_stock_quantity(
def get_reserved_stock_quantity_bulk(
stocks: Iterable[Stock],
checkout_lines: Iterable["CheckoutLine"],
-) -> Dict[int, int]:
- reservations: Dict[int, int] = defaultdict(int)
+) -> dict[int, int]:
+ reservations: dict[int, int] = defaultdict(int)
if not stocks:
return reservations
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index dfa4980a74..1189ad6d14 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -1,6 +1,7 @@
import math
from collections import defaultdict, namedtuple
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, cast
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Any, Optional, cast
from uuid import UUID
from django.db import transaction
@@ -46,7 +47,7 @@ def allocate_stocks(
channel: "Channel",
manager: PluginsManager,
collection_point_pk: Optional[UUID] = None,
- additional_filter_lookup: Optional[Dict[str, Any]] = None,
+ additional_filter_lookup: Optional[dict[str, Any]] = None,
check_reservations: bool = False,
checkout_lines: Optional[Iterable["CheckoutLine"]] = None,
):
@@ -89,7 +90,7 @@ def allocate_stocks(
)
stocks_id = (stock.pop("id") for stock in stocks)
- quantity_reservation_for_stocks: Dict = _prepare_stock_to_reserved_quantity_map(
+ quantity_reservation_for_stocks: dict = _prepare_stock_to_reserved_quantity_map(
checkout_lines, check_reservations, stocks_id
)
@@ -101,7 +102,7 @@ def allocate_stocks(
.values("stock")
.annotate(quantity_allocated_sum=Sum("quantity_allocated"))
)
- quantity_allocation_for_stocks: Dict = defaultdict(int)
+ quantity_allocation_for_stocks: dict = defaultdict(int)
for allocation_data in quantity_allocation_list:
quantity_allocation_for_stocks[allocation_data["stock"]] += allocation_data[
"quantity_allocated_sum"
@@ -115,13 +116,13 @@ def allocate_stocks(
collection_point_pk,
)
- variant_to_stocks: Dict[int, List[StockData]] = defaultdict(list)
+ variant_to_stocks: dict[int, list[StockData]] = defaultdict(list)
for stock_data in stocks:
variant = stock_data.pop("product_variant")
variant_to_stocks[variant].append(StockData(**stock_data))
- insufficient_stock: List[InsufficientStockData] = []
- allocations: List[Allocation] = []
+ insufficient_stock: list[InsufficientStockData] = []
+ allocations: list[Allocation] = []
for line_info in order_lines_info:
line_info.variant = cast(ProductVariant, line_info.variant)
stock_allocations = variant_to_stocks[line_info.variant.pk]
@@ -164,7 +165,7 @@ def _prepare_stock_to_reserved_quantity_map(
checkout_lines, check_reservations, stocks_id
):
"""Prepare stock id to quantity reserved map for provided stock ids."""
- quantity_reservation_for_stocks: Dict = defaultdict(int)
+ quantity_reservation_for_stocks: dict = defaultdict(int)
if check_reservations:
quantity_reservation = (
@@ -187,9 +188,9 @@ def _prepare_stock_to_reserved_quantity_map(
def sort_stocks(
allocation_strategy: str,
- stocks: List[dict],
+ stocks: list[dict],
channel: "Channel",
- quantity_allocation_for_stocks: Dict[int, int],
+ quantity_allocation_for_stocks: dict[int, int],
collection_point_pk: Optional[UUID] = None,
):
warehouse_ids = [stock_data["warehouse_id"] for stock_data in stocks]
@@ -235,10 +236,10 @@ def sort_stocks(
def _create_allocations(
line_info: "OrderLineInfo",
- stocks: List[StockData],
+ stocks: list[StockData],
stocks_allocations: dict,
stocks_reservations: dict,
- insufficient_stock: List[InsufficientStockData],
+ insufficient_stock: list[InsufficientStockData],
):
quantity = line_info.quantity
quantity_allocated = 0
@@ -299,7 +300,7 @@ def deallocate_stock(
.order_by("stock__pk")
)
- line_to_allocations: Dict[UUID, List[Allocation]] = defaultdict(list)
+ line_to_allocations: dict[UUID, list[Allocation]] = defaultdict(list)
for allocation in lines_allocations:
line_to_allocations[allocation.order_line_id].append(allocation)
@@ -414,7 +415,7 @@ def increase_allocations(
)
# evaluate allocations query to trigger select_for_update lock
allocation_pks_to_delete = [alloc.pk for alloc in allocations]
- allocation_quantity_map: Dict[UUID, list] = defaultdict(list)
+ allocation_quantity_map: dict[UUID, list] = defaultdict(list)
for alloc in allocations:
allocation_quantity_map[alloc.order_line.pk].append(alloc.quantity_allocated)
@@ -483,7 +484,7 @@ def decrease_stock(
.order_by("pk")
)
- variant_and_warehouse_to_stock: Dict[int, Dict[UUID, Stock]] = defaultdict(dict)
+ variant_and_warehouse_to_stock: dict[int, dict[UUID, Stock]] = defaultdict(dict)
for stock in stocks:
variant_and_warehouse_to_stock[stock.product_variant_id][
stock.warehouse_id
@@ -499,7 +500,7 @@ def decrease_stock(
)
if update_stocks:
- quantity_allocation_for_stocks: Dict[int, int] = defaultdict(int)
+ quantity_allocation_for_stocks: dict[int, int] = defaultdict(int)
for allocation in quantity_allocation_list:
quantity_allocation_for_stocks[allocation["stock"]] += allocation[
"quantity_allocated__sum"
@@ -523,11 +524,11 @@ def decrease_stock(
def _decrease_stocks_quantity(
order_lines_info: Iterable["OrderLineInfo"],
- variant_and_warehouse_to_stock: Dict[int, Dict[UUID, Stock]],
- quantity_allocation_for_stocks: Dict[int, int],
+ variant_and_warehouse_to_stock: dict[int, dict[UUID, Stock]],
+ quantity_allocation_for_stocks: dict[int, int],
allow_stock_to_be_exceeded: bool = False,
):
- insufficient_stocks: List[InsufficientStockData] = []
+ insufficient_stocks: list[InsufficientStockData] = []
stocks_to_update = []
for line_info in order_lines_info:
variant = line_info.variant
@@ -668,7 +669,7 @@ def allocate_preorders(
.values("product_variant_channel_listing")
.annotate(preorder_quantity_allocated=Sum("quantity"))
)
- quantity_allocation_for_channel: Dict = defaultdict(int)
+ quantity_allocation_for_channel: dict = defaultdict(int)
for allocation in quantity_allocation_list:
quantity_allocation_for_channel[
allocation["product_variant_channel_listing"]
@@ -700,7 +701,7 @@ def allocate_preorders(
.values("product_variant_channel_listing")
.annotate(quantity_reserved_sum=Sum("quantity_reserved"))
)
- listings_reservations: Dict = defaultdict(int)
+ listings_reservations: dict = defaultdict(int)
for reservation in quantity_reservation_list:
listings_reservations[
reservation["product_variant_channel_listing"]
@@ -708,14 +709,14 @@ def allocate_preorders(
else:
listings_reservations = defaultdict(int)
- variants_global_allocations: Dict[int, int] = defaultdict(int)
+ variants_global_allocations: dict[int, int] = defaultdict(int)
for channel_listing in all_variants_channel_listings:
variants_global_allocations[
channel_listing["variant_id"]
] += quantity_allocation_for_channel[channel_listing["id"]]
- insufficient_stocks: List[InsufficientStockData] = []
- allocations: List[PreorderAllocation] = []
+ insufficient_stocks: list[InsufficientStockData] = []
+ allocations: list[PreorderAllocation] = []
for line_info in order_lines_info:
variant = cast(ProductVariant, line_info.variant)
allocation_item, insufficient_stock = _create_preorder_allocation(
@@ -751,12 +752,12 @@ def get_order_lines_with_preorder(
def _create_preorder_allocation(
line_info: "OrderLineInfo",
- variant_channel_data: Tuple[int, Optional[int]],
+ variant_channel_data: tuple[int, Optional[int]],
variant_global_allocation: int,
- variants_channel_listings: List[int],
- quantity_allocation_for_channel: Dict[int, int],
- listings_reservations: Dict[int, int],
-) -> Tuple[Optional[PreorderAllocation], Optional[InsufficientStockData]]:
+ variants_channel_listings: list[int],
+ quantity_allocation_for_channel: dict[int, int],
+ listings_reservations: dict[int, int],
+) -> tuple[Optional[PreorderAllocation], Optional[InsufficientStockData]]:
variant = cast(ProductVariant, line_info.variant)
quantity = line_info.quantity
channel_listing_id, channel_quantity_threshold = variant_channel_data
@@ -891,10 +892,8 @@ def _get_stock_for_preorder_allocation(
raise PreorderAllocationError(preorder_allocation.order_line)
stock = list(
- (
- Stock.objects.select_for_update(of=("self",)).filter(
- warehouse=warehouse, product_variant=product_variant
- )
+ Stock.objects.select_for_update(of=("self",)).filter(
+ warehouse=warehouse, product_variant=product_variant
)
)
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index 551e053bcf..600342bc5c 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -1,10 +1,9 @@
import itertools
import uuid
+from collections.abc import Iterable
from typing import (
TYPE_CHECKING,
- Iterable,
Optional,
- Set,
TypedDict,
TypeVar,
Union,
@@ -220,7 +219,7 @@ class Warehouse(ModelWithMetadata, ModelWithExternalReference):
return self.name
@property
- def countries(self) -> Set[str]:
+ def countries(self) -> set[str]:
shipping_zones = self.shipping_zones.all()
return set(itertools.chain(*[zone.countries for zone in shipping_zones]))
diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.py
index b61bba5ada..5ff9fbdf87 100644
--- a/saleor/warehouse/reservations.py
+++ b/saleor/warehouse/reservations.py
@@ -1,6 +1,7 @@
from collections import defaultdict, namedtuple
+from collections.abc import Iterable
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
from django.db.models import F, Sum
from django.db.models.functions import Coalesce
@@ -116,7 +117,7 @@ def reserve_stocks(
.values("stock")
.annotate(quantity_allocated_sum=Sum("quantity_allocated"))
)
- quantity_allocation_for_stocks: Dict = defaultdict(int)
+ quantity_allocation_for_stocks: dict = defaultdict(int)
for allocation in quantity_allocation_list:
quantity_allocation_for_stocks[allocation["stock"]] += allocation[
"quantity_allocated_sum"
@@ -132,7 +133,7 @@ def reserve_stocks(
.values("stock")
.annotate(quantity_reserved_sum=Sum("quantity_reserved"))
)
- quantity_reservation_for_stocks: Dict = defaultdict(int)
+ quantity_reservation_for_stocks: dict = defaultdict(int)
for reservation in quantity_reservation_list:
quantity_reservation_for_stocks[reservation["stock"]] += reservation[
"quantity_reserved_sum"
@@ -145,13 +146,13 @@ def reserve_stocks(
quantity_allocation_for_stocks,
)
- variant_to_stocks: Dict[int, List[StockData]] = defaultdict(list)
+ variant_to_stocks: dict[int, list[StockData]] = defaultdict(list)
for stock_data in stocks:
variant = stock_data.pop("product_variant")
variant_to_stocks[variant].append(StockData(**stock_data))
- insufficient_stocks: List[InsufficientStockData] = []
- reservations: List[Reservation] = []
+ insufficient_stocks: list[InsufficientStockData] = []
+ reservations: list[Reservation] = []
for line in checkout_lines:
stock_reservations = variant_to_stocks[line.variant_id]
insufficient_stocks, reserved_items = _create_stock_reservations(
@@ -177,12 +178,12 @@ def reserve_stocks(
def _create_stock_reservations(
line: "CheckoutLine",
variant: "ProductVariant",
- stocks: List[StockData],
+ stocks: list[StockData],
quantity_allocation_for_stocks: dict,
quantity_reservation_for_stocks: dict,
- insufficient_stocks: List[InsufficientStockData],
+ insufficient_stocks: list[InsufficientStockData],
reserved_until: datetime,
-) -> Tuple[List[InsufficientStockData], List[Reservation]]:
+) -> tuple[list[InsufficientStockData], list[Reservation]]:
quantity = line.quantity
quantity_reserved = 0
reservations = []
@@ -271,7 +272,7 @@ def reserve_preorders(
if not checkout_lines_to_reserve:
return
- variant_channels: Dict[int, List[ProductVariantChannelListing]] = defaultdict(list)
+ variant_channels: dict[int, list[ProductVariantChannelListing]] = defaultdict(list)
for channel_listing in all_variants_channel_listings:
variant_channels[channel_listing.variant_id].append(channel_listing)
@@ -283,12 +284,12 @@ def reserve_preorders(
for variant_id, channel_listings in variant_channels.items()
}
- listings_reservations: Dict = get_listings_reservations(
+ listings_reservations: dict = get_listings_reservations(
checkout_lines, all_variants_channel_listings
)
- insufficient_stocks: List[InsufficientStockData] = []
- reservations: List[PreorderReservation] = []
+ insufficient_stocks: list[InsufficientStockData] = []
+ reservations: list[PreorderReservation] = []
for line in checkout_lines_to_reserve:
insufficient_stocks, reservation = _create_preorder_reservation(
line,
@@ -318,10 +319,10 @@ def _create_preorder_reservation(
line: "CheckoutLine",
variant: "ProductVariant",
listing: "ProductVariantChannelListing",
- all_listings: List["ProductVariantChannelListing"],
+ all_listings: list["ProductVariantChannelListing"],
global_allocations: int,
- listings_reservations: Dict[int, int],
- insufficient_stocks: List[InsufficientStockData],
+ listings_reservations: dict[int, int],
+ insufficient_stocks: list[InsufficientStockData],
reserved_until: datetime,
):
if listing.preorder_quantity_threshold is not None:
@@ -370,7 +371,7 @@ def _create_preorder_reservation(
def get_checkout_lines_to_reserve(
lines: Iterable["CheckoutLine"],
- variants_map: Dict[int, "ProductVariant"],
+ variants_map: dict[int, "ProductVariant"],
) -> Iterable["CheckoutLine"]:
"""Return checkout lines which can be reserved."""
valid_lines = []
@@ -400,7 +401,7 @@ def get_reservation_length(site, user) -> Optional[int]:
def get_listings_reservations(
checkout_lines: Optional[Iterable["CheckoutLine"]],
all_variants_channel_listings,
-) -> Dict[int, int]:
+) -> dict[int, int]:
quantity_reservation_list = (
PreorderReservation.objects.filter(
product_variant_channel_listing__in=all_variants_channel_listings,
@@ -411,7 +412,7 @@ def get_listings_reservations(
.values("product_variant_channel_listing")
.annotate(quantity_reserved_sum=Sum("quantity_reserved"))
)
- listings_reservations: Dict = defaultdict(int)
+ listings_reservations: dict = defaultdict(int)
for reservation in quantity_reservation_list:
listings_reservations[
diff --git a/saleor/webhook/observability/buffers.py b/saleor/webhook/observability/buffers.py
index d1b94eab23..1d7aa7cbee 100644
--- a/saleor/webhook/observability/buffers.py
+++ b/saleor/webhook/observability/buffers.py
@@ -1,7 +1,7 @@
import math
import pickle
import zlib
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Optional
from asgiref.local import Local
from django.conf import settings
@@ -47,14 +47,14 @@ class BaseBuffer:
"subclasses of BaseBuffer must provide a put_event() method"
)
- def put_events(self, events: List[Any]) -> int:
+ def put_events(self, events: list[Any]) -> int:
raise NotImplementedError(
"subclasses of BaseBuffer must provide a put_events() method"
)
def put_multi_key_events(
- self, events_dict: Dict[KEY_TYPE, List[Any]]
- ) -> Dict[KEY_TYPE, int]:
+ self, events_dict: dict[KEY_TYPE, list[Any]]
+ ) -> dict[KEY_TYPE, int]:
raise NotImplementedError(
"subclasses of BaseBuffer must provide a put_events_multi_buffer() method"
)
@@ -64,12 +64,12 @@ class BaseBuffer:
"subclasses of BaseBuffer must provide a pop_events() method"
)
- def pop_events(self) -> List[Any]:
+ def pop_events(self) -> list[Any]:
raise NotImplementedError(
"subclasses of BaseBuffer must provide a pop_events() method"
)
- def pop_events_get_size(self) -> Tuple[List[Any], int]:
+ def pop_events_get_size(self) -> tuple[list[Any], int]:
raise NotImplementedError(
"subclasses of BaseBuffer must provide a pop_events_get_size() method"
)
@@ -89,7 +89,7 @@ class BaseBuffer:
class RedisBuffer(BaseBuffer):
- _pools: Dict[str, ConnectionPool] = {}
+ _pools: dict[str, ConnectionPool] = {}
_socket_connect_timeout = 0.25
_client_name = "observability_buffer"
@@ -121,7 +121,7 @@ class RedisBuffer(BaseBuffer):
return self._client
def _put_events(
- self, key: KEY_TYPE, events: List[Any], client: Optional[Redis] = None
+ self, key: KEY_TYPE, events: list[Any], client: Optional[Redis] = None
) -> int:
start_index = -self.max_size
events_data = [self.encode(event) for event in events[start_index:]]
@@ -132,7 +132,7 @@ class RedisBuffer(BaseBuffer):
client.expire(key, self.timeout)
return max(0, len(events) - self.max_size)
- def put_events(self, events: List[Any]) -> int:
+ def put_events(self, events: list[Any]) -> int:
with self.client.pipeline(transaction=False) as pipe:
dropped = self._put_events(self.key, events, client=pipe)
result = pipe.execute()
@@ -142,10 +142,10 @@ class RedisBuffer(BaseBuffer):
return self.put_events([event])
def put_multi_key_events(
- self, events_dict: Dict[KEY_TYPE, List[Any]]
- ) -> Dict[KEY_TYPE, int]:
+ self, events_dict: dict[KEY_TYPE, list[Any]]
+ ) -> dict[KEY_TYPE, int]:
keys = list(events_dict.keys())
- trimmed: Dict[KEY_TYPE, int] = {}
+ trimmed: dict[KEY_TYPE, int] = {}
if not keys:
return trimmed
with self.client.pipeline(transaction=False) as pipe:
@@ -157,7 +157,7 @@ class RedisBuffer(BaseBuffer):
trimmed[key] += max(0, buffer_len - self.max_size)
return trimmed
- def _pop_events(self, key: KEY_TYPE, batch_size: int) -> Tuple[List[Any], int]:
+ def _pop_events(self, key: KEY_TYPE, batch_size: int) -> tuple[list[Any], int]:
events = []
with self.client.pipeline(transaction=False) as pipe:
pipe.llen(key)
@@ -175,11 +175,11 @@ class RedisBuffer(BaseBuffer):
events, _ = self._pop_events(self.key, batch_size=1)
return events[0] if events else None
- def pop_events(self) -> List[Any]:
+ def pop_events(self) -> list[Any]:
events, _ = self._pop_events(self.key, self.batch_size)
return events
- def pop_events_get_size(self) -> Tuple[List[Any], int]:
+ def pop_events_get_size(self) -> tuple[list[Any], int]:
return self._pop_events(self.key, self.batch_size)
def clear(self) -> int:
diff --git a/saleor/webhook/observability/obfuscation.py b/saleor/webhook/observability/obfuscation.py
index c1aa74ab8a..93c7540064 100644
--- a/saleor/webhook/observability/obfuscation.py
+++ b/saleor/webhook/observability/obfuscation.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union, cast
+from typing import TYPE_CHECKING, Any, Optional, Union, cast
from urllib.parse import urlparse, urlunparse
from graphql import (
@@ -40,10 +40,10 @@ MASK = "***"
def filter_and_hide_headers(
- headers: Dict[str, str],
+ headers: dict[str, str],
allowed=ALLOWED_HEADERS,
sensitive=SENSITIVE_HEADERS,
-) -> Dict[str, str]:
+) -> dict[str, str]:
filtered_headers = {}
for key, val in headers.items():
lowered = key.lower()
@@ -90,7 +90,7 @@ class ContainSensitiveField(ValidationRule):
def contain_sensitive_field(self, node: GraphQLNode, type_def) -> bool:
if isinstance(node, FragmentSpread) or not node.selection_set:
return False
- fields: Dict[str, GraphQLField] = {}
+ fields: dict[str, GraphQLField] = {}
if isinstance(type_def, (GraphQLObjectType, GraphQLInterfaceType)):
fields = type_def.fields
for child_node in node.selection_set.selections:
@@ -138,8 +138,8 @@ class ContainSensitiveField(ValidationRule):
node: Any,
key: Optional[Union[int, str]],
parent: Any,
- path: List[Union[int, str]],
- ancestors: List[Any],
+ path: list[Union[int, str]],
+ ancestors: list[Any],
):
if isinstance(node, OperationDefinition):
self.enter_operation_definition(node, key, parent, path, ancestors)
@@ -175,7 +175,7 @@ def _contain_sensitive_field(
document: "GraphQLDocument", sensitive_fields: SensitiveFieldsMap
):
validator = cast(
- Type[ValidationRule], ContainSensitiveField(sensitive_fields=sensitive_fields)
+ type[ValidationRule], ContainSensitiveField(sensitive_fields=sensitive_fields)
)
try:
validate(document.schema, document.document_ast, [validator])
diff --git a/saleor/webhook/observability/payload_schema.py b/saleor/webhook/observability/payload_schema.py
index 419f45d1d2..ae9ed18484 100644
--- a/saleor/webhook/observability/payload_schema.py
+++ b/saleor/webhook/observability/payload_schema.py
@@ -1,7 +1,7 @@
from datetime import datetime
from enum import Enum
from json.encoder import ESCAPE_ASCII, ESCAPE_DCT
-from typing import List, Optional, Tuple, TypedDict
+from typing import Optional, TypedDict
class JsonTruncText:
@@ -65,7 +65,7 @@ class ObservabilityEventTypes(str, Enum):
EVENT_DELIVERY_ATTEMPT = "event_delivery_attempt"
-HttpHeaders = List[Tuple[str, str]]
+HttpHeaders = list[tuple[str, str]]
class App(TypedDict):
@@ -111,7 +111,7 @@ class ApiCallPayload(ObservabilityEventBase):
request: ApiCallRequest
response: ApiCallResponse
app: Optional[App]
- gql_operations: List[GraphQLOperation]
+ gql_operations: list[GraphQLOperation]
class EventDeliveryPayload(TypedDict):
diff --git a/saleor/webhook/observability/payloads.py b/saleor/webhook/observability/payloads.py
index 0e33e4f37f..4694c31814 100644
--- a/saleor/webhook/observability/payloads.py
+++ b/saleor/webhook/observability/payloads.py
@@ -1,7 +1,7 @@
import json
import uuid
from collections.abc import Mapping
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, Optional
import graphene
from django.core.serializers.json import DjangoJSONEncoder
@@ -83,7 +83,7 @@ GQL_OPERATION_PLACEHOLDER = GraphQLOperation(
GQL_OPERATION_PLACEHOLDER_SIZE = len(dump_payload(GQL_OPERATION_PLACEHOLDER))
-def serialize_headers(headers: Optional[Dict[str, str]]) -> HttpHeaders:
+def serialize_headers(headers: Optional[dict[str, str]]) -> HttpHeaders:
if headers:
return list(filter_and_hide_headers(headers).items())
return []
@@ -91,7 +91,7 @@ def serialize_headers(headers: Optional[Dict[str, str]]) -> HttpHeaders:
def serialize_gql_operation_result(
operation: "GraphQLOperationResponse", bytes_limit: int
-) -> Tuple[GraphQLOperation, int]:
+) -> tuple[GraphQLOperation, int]:
bytes_limit -= GQL_OPERATION_PLACEHOLDER_SIZE
if bytes_limit < 0:
raise ApiCallTruncationError("serialize_gql_operation_result", bytes_limit, 0)
@@ -125,8 +125,8 @@ def serialize_gql_operation_result(
def serialize_gql_operation_results(
- operations: List["GraphQLOperationResponse"], bytes_limit: int
-) -> List[GraphQLOperation]:
+ operations: list["GraphQLOperationResponse"], bytes_limit: int
+) -> list[GraphQLOperation]:
payload_size = len(operations) * GQL_OPERATION_PLACEHOLDER_SIZE
if bytes_limit - payload_size < 0:
raise ApiCallTruncationError(
@@ -135,7 +135,7 @@ def serialize_gql_operation_results(
payload_size,
gql_operations_count=len(operations),
)
- payloads: List[GraphQLOperation] = []
+ payloads: list[GraphQLOperation] = []
for i, operation in enumerate(operations):
payload_limit = bytes_limit // (len(operations) - i)
payload, left_bytes = serialize_gql_operation_result(operation, payload_limit)
@@ -148,7 +148,7 @@ def serialize_gql_operation_results(
def generate_api_call_payload(
request: HttpRequest,
response: HttpResponse,
- gql_operations: List["GraphQLOperationResponse"],
+ gql_operations: list["GraphQLOperationResponse"],
bytes_limit: int,
) -> ApiCallPayload:
payload = ApiCallPayload(
diff --git a/saleor/webhook/observability/sensitive_data.py b/saleor/webhook/observability/sensitive_data.py
index f8f68fb07a..96ee204b76 100644
--- a/saleor/webhook/observability/sensitive_data.py
+++ b/saleor/webhook/observability/sensitive_data.py
@@ -8,7 +8,6 @@ SENSITIVE_GQL_FIELDS is a dict of sets representing fields of GraphGL types to a
- Type
- Fields
"""
-from typing import Dict, Set
from ...app.headers import AppHeaders, DeprecatedAppHeaders
@@ -43,7 +42,7 @@ SENSITIVE_HEADERS = {
}
}
-SensitiveFieldsMap = Dict[str, Set[str]]
+SensitiveFieldsMap = dict[str, set[str]]
SENSITIVE_GQL_FIELDS: SensitiveFieldsMap = {
"RefreshToken": {"token"},
"CreateToken": {"token", "refreshToken", "csrfToken"},
diff --git a/saleor/webhook/observability/tests/conftest.py b/saleor/webhook/observability/tests/conftest.py
index af092647f7..39a244fb18 100644
--- a/saleor/webhook/observability/tests/conftest.py
+++ b/saleor/webhook/observability/tests/conftest.py
@@ -1,4 +1,4 @@
-from typing import Dict, Optional
+from typing import Optional
from unittest.mock import patch
import fakeredis
@@ -23,8 +23,8 @@ def gql_operation_factory():
def factory(
query_string: str,
operation_name: Optional[str] = None,
- variables: Optional[Dict] = None,
- result: Optional[Dict] = None,
+ variables: Optional[dict] = None,
+ result: Optional[dict] = None,
result_invalid=False,
) -> GraphQLOperationResponse:
query = backend.document_from_string(schema, query_string)
diff --git a/saleor/webhook/observability/utils.py b/saleor/webhook/observability/utils.py
index d19b36d96c..2fc07fd6fd 100644
--- a/saleor/webhook/observability/utils.py
+++ b/saleor/webhook/observability/utils.py
@@ -1,11 +1,12 @@
import functools
import logging
+from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import partial
from time import monotonic
-from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, Callable, Optional
from asgiref.local import Local
from django.conf import settings
@@ -32,7 +33,7 @@ logger = logging.getLogger(__name__)
CACHE_TIMEOUT = parse("2 minutes")
BUFFER_KEY = "observability_buffer"
WEBHOOKS_KEY = "observability_webhooks"
-_active_webhooks_exists_cache: Dict[str, Tuple[bool, float]] = {}
+_active_webhooks_exists_cache: dict[str, tuple[bool, float]] = {}
_context = Local()
@@ -48,14 +49,14 @@ def get_buffer_name() -> str:
return cache.make_key(BUFFER_KEY)
-_webhooks_mem_cache: Dict[str, Tuple[List[WebhookData], float]] = {}
+_webhooks_mem_cache: dict[str, tuple[list[WebhookData], float]] = {}
def get_webhooks_clear_mem_cache():
_webhooks_mem_cache.clear()
-def get_webhooks(timeout=CACHE_TIMEOUT) -> List[WebhookData]:
+def get_webhooks(timeout=CACHE_TIMEOUT) -> list[WebhookData]:
with opentracing_trace("get_observability_webhooks", "webhooks"):
buffer_name = get_buffer_name()
if cached := _webhooks_mem_cache.get(buffer_name, None):
@@ -101,7 +102,7 @@ def put_event(generate_payload: Callable[[], Any]):
logger.error("Observability event dropped.", exc_info=True)
-def pop_events_with_remaining_size() -> Tuple[List[Any], int]:
+def pop_events_with_remaining_size() -> tuple[list[Any], int]:
with opentracing_trace("pop_events", "buffer"):
try:
buffer = get_buffer(get_buffer_name())
@@ -117,14 +118,14 @@ def pop_events_with_remaining_size() -> Tuple[List[Any], int]:
class GraphQLOperationResponse:
name: Optional[str] = None
query: Optional[GraphQLDocument] = None
- variables: Optional[Dict] = None
- result: Optional[Dict] = None
+ variables: Optional[dict] = None
+ result: Optional[dict] = None
result_invalid: bool = False
class ApiCall:
def __init__(self, request: "HttpRequest"):
- self.gql_operations: List[GraphQLOperationResponse] = []
+ self.gql_operations: list[GraphQLOperationResponse] = []
self.response: Optional["HttpResponse"] = None
self._reported = False
self.request = request
diff --git a/saleor/webhook/payload_serializers.py b/saleor/webhook/payload_serializers.py
index c83d1779d0..fbe1dc3fcf 100644
--- a/saleor/webhook/payload_serializers.py
+++ b/saleor/webhook/payload_serializers.py
@@ -1,6 +1,6 @@
from collections import OrderedDict
from collections.abc import Iterable
-from typing import Any, Dict, Optional
+from typing import Any, Optional
import graphene
from django.core.serializers.json import Serializer as JSONSerializer
@@ -67,7 +67,7 @@ class PayloadSerializer(JSONSerializer):
obj_id = graphene.Node.to_global_id(
obj._meta.object_name, getattr(obj, self.pk_field_name)
)
- data: Dict[str, Optional[Any]] = {}
+ data: dict[str, Optional[Any]] = {}
if self.dump_type_name:
data["type"] = str(obj._meta.object_name)
data[self.obj_id_name] = obj_id
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index d9c62684e0..7f3dcb2ce3 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -1,17 +1,13 @@
import json
import uuid
from collections import defaultdict
+from collections.abc import Iterable
from dataclasses import asdict
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
- DefaultDict,
- Dict,
- Iterable,
- List,
Optional,
- Set,
Union,
)
@@ -128,7 +124,7 @@ def generate_requestor(requestor: Optional["RequestorOrLazyObject"] = None):
return {"id": requestor.name, "type": "app"} # type: ignore
-def generate_meta(*, requestor_data: Dict[str, Any], camel_case=False, **kwargs):
+def generate_meta(*, requestor_data: dict[str, Any], camel_case=False, **kwargs):
meta_result = {
"issued_at": timezone.now().isoformat(),
"version": __version__,
@@ -404,26 +400,26 @@ def _generate_order_payment_payload(payments: Iterable["Payment"]):
def _calculate_added(
- previous_catalogue: DefaultDict[str, Set[str]],
- current_catalogue: DefaultDict[str, Set[str]],
+ previous_catalogue: defaultdict[str, set[str]],
+ current_catalogue: defaultdict[str, set[str]],
key: str,
-) -> List[str]:
+) -> list[str]:
return list(current_catalogue[key] - previous_catalogue[key])
def _calculate_removed(
- previous_catalogue: DefaultDict[str, Set[str]],
- current_catalogue: DefaultDict[str, Set[str]],
+ previous_catalogue: defaultdict[str, set[str]],
+ current_catalogue: defaultdict[str, set[str]],
key: str,
-) -> List[str]:
+) -> list[str]:
return _calculate_added(current_catalogue, previous_catalogue, key)
@traced_payload_generator
def generate_sale_payload(
promotion: "Promotion",
- previous_catalogue: Optional[DefaultDict[str, Set[str]]] = None,
- current_catalogue: Optional[DefaultDict[str, Set[str]]] = None,
+ previous_catalogue: Optional[defaultdict[str, set[str]]] = None,
+ current_catalogue: Optional[defaultdict[str, set[str]]] = None,
requestor: Optional["RequestorOrLazyObject"] = None,
):
if previous_catalogue is None:
@@ -470,7 +466,7 @@ def generate_sale_payload(
@traced_payload_generator
def generate_sale_toggle_payload(
promotion: "Promotion",
- catalogue: DefaultDict[str, Set[str]],
+ catalogue: defaultdict[str, set[str]],
requestor: Optional["RequestorOrLazyObject"] = None,
):
serializer = PayloadSerializer()
@@ -747,7 +743,7 @@ def generate_product_payload(
)
),
"variants": lambda x: json.loads(
- (generate_product_variant_payload(x, with_meta=False))
+ generate_product_variant_payload(x, with_meta=False)
),
},
)
@@ -1222,7 +1218,7 @@ def _generate_payload_for_shipping_method(method: ShippingMethodData):
@traced_payload_generator
def generate_excluded_shipping_methods_for_order_payload(
order: "Order",
- available_shipping_methods: List[ShippingMethodData],
+ available_shipping_methods: list[ShippingMethodData],
):
order_data = json.loads(generate_order_payload(order))[0]
payload = {
@@ -1238,7 +1234,7 @@ def generate_excluded_shipping_methods_for_order_payload(
@traced_payload_generator
def generate_excluded_shipping_methods_for_checkout_payload(
checkout: "Checkout",
- available_shipping_methods: List[ShippingMethodData],
+ available_shipping_methods: list[ShippingMethodData],
):
checkout_data = json.loads(generate_checkout_payload(checkout))[0]
payload = {
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index 8406ec994a..3409178200 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -1,6 +1,7 @@
+from collections.abc import Iterable
from datetime import date, datetime
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Optional, Union
import graphene
from prices import Money
@@ -19,7 +20,7 @@ if TYPE_CHECKING:
from ..product.models import ProductVariant
-def serialize_checkout_lines(checkout: "Checkout") -> List[dict]:
+def serialize_checkout_lines(checkout: "Checkout") -> list[dict]:
data = []
channel = checkout.channel
currency = channel.currency_code
@@ -59,7 +60,7 @@ def serialize_checkout_lines(checkout: "Checkout") -> List[dict]:
return data
-def _get_checkout_line_payload_data(line_info: "CheckoutLineInfo") -> Dict[str, Any]:
+def _get_checkout_line_payload_data(line_info: "CheckoutLineInfo") -> dict[str, Any]:
line_id = graphene.Node.to_global_id("CheckoutLine", line_info.line.pk)
variant = line_info.variant
product = variant.product
@@ -79,7 +80,7 @@ def _get_checkout_line_payload_data(line_info: "CheckoutLineInfo") -> Dict[str,
def serialize_checkout_lines_for_tax_calculation(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
-) -> List[dict]:
+) -> list[dict]:
channel = checkout_info.channel
charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)
return [
@@ -105,7 +106,7 @@ def serialize_checkout_lines_for_tax_calculation(
def serialize_product_or_variant_attributes(
product_or_variant: Union["Product", "ProductVariant"]
-) -> List[Dict]:
+) -> list[dict]:
data = []
def _prepare_reference(attribute, attr_value):
@@ -124,7 +125,7 @@ def serialize_product_or_variant_attributes(
for attr in product_or_variant.attributes.all():
attr_id = graphene.Node.to_global_id("Attribute", attr.assignment.attribute_id)
attribute = attr.assignment.attribute
- attr_data: Dict[Any, Any] = {
+ attr_data: dict[Any, Any] = {
"name": attribute.name,
"input_type": attribute.input_type,
"slug": attribute.slug,
@@ -136,8 +137,8 @@ def serialize_product_or_variant_attributes(
for attr_value in attr.values.all():
attr_slug = attr_value.slug
- value: Dict[
- str, Optional[Union[str, datetime, date, bool, Dict[str, Any]]]
+ value: dict[
+ str, Optional[Union[str, datetime, date, bool, dict[str, Any]]]
] = {
"name": attr_value.name,
"slug": attr_slug,
diff --git a/saleor/webhook/tests/test_utils.py b/saleor/webhook/tests/test_utils.py
index 17ff6b62eb..fbc9ded266 100644
--- a/saleor/webhook/tests/test_utils.py
+++ b/saleor/webhook/tests/test_utils.py
@@ -1,5 +1,3 @@
-from typing import Type
-
import pytest
from ...app.models import App
@@ -130,7 +128,7 @@ def test_get_webhook_for_event_not_returning_any_webhook_for_sync_event_types(
],
)
def test_truncation_error_extra_fields(
- error: Type[TruncationError], event_type: ObservabilityEventTypes
+ error: type[TruncationError], event_type: ObservabilityEventTypes
):
operation, bytes_limit, payload_size = "operation_name", 100, 102
kwargs = dict(extra_kwarg_a="a", extra_kwarg_b="b")
diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.py
index 4004ccd3ef..ddc69efa77 100644
--- a/saleor/webhook/transport/asynchronous/transport.py
+++ b/saleor/webhook/transport/asynchronous/transport.py
@@ -1,6 +1,7 @@
import json
import logging
-from typing import TYPE_CHECKING, Any, List, Sequence
+from collections.abc import Sequence
+from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
from celery import group
@@ -42,7 +43,7 @@ task_logger = get_task_logger(__name__)
def create_deliveries_for_subscriptions(
event_type, subscribable_object, webhooks, requestor=None
-) -> List[EventDelivery]:
+) -> list[EventDelivery]:
"""Create a list of event deliveries with payloads based on subscription query.
It uses a subscription query, defined for webhook to explicitly determine
@@ -105,7 +106,7 @@ def create_event_delivery_list_for_webhooks(
webhooks: Sequence["Webhook"],
event_payload: "EventPayload",
event_type: str,
-) -> List[EventDelivery]:
+) -> list[EventDelivery]:
event_deliveries = EventDelivery.objects.bulk_create(
[
EventDelivery(
@@ -221,7 +222,7 @@ def send_webhook_request_async(self, event_delivery_id):
clear_successful_delivery(delivery)
-def send_observability_events(webhooks: List[WebhookData], events: List[Any]):
+def send_observability_events(webhooks: list[WebhookData], events: list[Any]):
event_type = WebhookEventAsyncType.OBSERVABILITY
for webhook in webhooks:
scheme = urlparse(webhook.target_url).scheme.lower()
diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.py
index fa256eb68d..f84640feee 100644
--- a/saleor/webhook/transport/shipping.py
+++ b/saleor/webhook/transport/shipping.py
@@ -2,7 +2,7 @@ import base64
import json
import logging
from collections import defaultdict
-from typing import Any, Callable, Dict, List, Optional, Union
+from typing import Any, Callable, Optional, Union
from django.conf import settings
from django.core.cache import cache
@@ -54,7 +54,7 @@ def convert_to_app_id_with_identifier(shipping_app_id: str):
def parse_list_shipping_methods_response(
response_data: Any, app: "App"
-) -> List["ShippingMethodData"]:
+) -> list["ShippingMethodData"]:
shipping_methods = []
for shipping_method_data in response_data:
method_id = shipping_method_data.get("id")
@@ -93,7 +93,7 @@ def get_excluded_shipping_methods_or_fetch(
payload: str,
cache_key: str,
subscribable_object: Optional[Union["Order", "Checkout"]],
-) -> Dict[str, List[ExcludedShippingMethod]]:
+) -> dict[str, list[ExcludedShippingMethod]]:
"""Return data of all excluded shipping methods.
The data will be fetched from the cache. If missing it will fetch it from all
@@ -129,11 +129,11 @@ def get_excluded_shipping_methods_or_fetch(
def get_excluded_shipping_data(
event_type: str,
- previous_value: List[ExcludedShippingMethod],
+ previous_value: list[ExcludedShippingMethod],
payload_fun: Callable[[], str],
cache_key: str,
subscribable_object: Optional[Union["Order", "Checkout"]],
-) -> List[ExcludedShippingMethod]:
+) -> list[ExcludedShippingMethod]:
"""Exclude not allowed shipping methods by sync webhook.
Fetch excluded shipping methods from sync webhooks and return them as a list of
@@ -146,7 +146,7 @@ def get_excluded_shipping_data(
webhook.
"""
- excluded_methods_map: Dict[str, List[ExcludedShippingMethod]] = defaultdict(list)
+ excluded_methods_map: dict[str, list[ExcludedShippingMethod]] = defaultdict(list)
webhooks = get_webhooks_for_event(event_type)
if webhooks:
payload = payload_fun()
@@ -171,7 +171,7 @@ def get_excluded_shipping_data(
def get_excluded_shipping_methods_from_response(
response_data: dict,
-) -> List[dict]:
+) -> list[dict]:
excluded_methods = []
for method_data in response_data.get("excluded_methods", []):
try:
@@ -192,8 +192,8 @@ def get_excluded_shipping_methods_from_response(
def parse_excluded_shipping_methods(
- excluded_methods: List[dict],
-) -> Dict[str, List[ExcludedShippingMethod]]:
+ excluded_methods: list[dict],
+) -> dict[str, list[ExcludedShippingMethod]]:
excluded_methods_map = defaultdict(list)
for excluded_method in excluded_methods:
method_id = excluded_method["id"]
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index 8291f376f0..fa019b9881 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -1,7 +1,7 @@
import json
import logging
from json import JSONDecodeError
-from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, TypeVar
+from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar
from urllib.parse import urlparse
from celery.utils.log import get_task_logger
@@ -85,7 +85,7 @@ def handle_transaction_request_task(self, delivery_id, request_event_id):
def _send_webhook_request_sync(
delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT, attempt=None
-) -> Tuple[WebhookResponse, Optional[Dict[Any, Any]]]:
+) -> tuple[WebhookResponse, Optional[dict[Any, Any]]]:
event_payload = delivery.payload
data = event_payload.payload
webhook = delivery.webhook
@@ -96,7 +96,7 @@ def _send_webhook_request_sync(
if parts.scheme.lower() not in [WebhookSchemes.HTTP, WebhookSchemes.HTTPS]:
delivery_update(delivery, EventDeliveryStatus.FAILED)
- raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
+ raise ValueError(f"Unknown webhook scheme: {parts.scheme!r}")
logger.debug(
"[Webhook] Sending payload to %r for event %r.",
@@ -158,7 +158,7 @@ def _send_webhook_request_sync(
def send_webhook_request_sync(
delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT
-) -> Optional[Dict[Any, Any]]:
+) -> Optional[dict[Any, Any]]:
response, response_data = _send_webhook_request_sync(delivery, timeout)
return response_data if response.status == EventDeliveryStatus.SUCCESS else None
@@ -257,7 +257,7 @@ def trigger_webhook_sync(
subscribable_object=None,
timeout=None,
request=None,
-) -> Optional[Dict[Any, Any]]:
+) -> Optional[dict[Any, Any]]:
"""Send a synchronous webhook request."""
if webhook.subscription_query:
delivery = create_delivery_for_subscription_sync_event(
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index b2fb6f761d..d1609d8415 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -6,7 +6,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from enum import Enum
from time import time
-from typing import Any, Callable, Dict, List, Optional
+from typing import Any, Callable, Optional
from urllib.parse import unquote, urlparse, urlunparse
import boto3
@@ -70,8 +70,8 @@ class PaymentAppData:
@dataclass
class WebhookResponse:
content: str
- request_headers: Optional[Dict] = None
- response_headers: Optional[Dict] = None
+ request_headers: Optional[dict] = None
+ response_headers: Optional[dict] = None
response_status_code: Optional[int] = None
status: str = EventDeliveryStatus.SUCCESS
duration: float = 0.0
@@ -101,7 +101,7 @@ def send_webhook_using_http(
signature,
event_type,
timeout=settings.WEBHOOK_TIMEOUT,
- custom_headers: Optional[Dict[str, str]] = None,
+ custom_headers: Optional[dict[str, str]] = None,
) -> WebhookResponse:
"""Send a webhook request using http / https protocol.
@@ -265,7 +265,7 @@ def send_webhook_using_scheme_method(
parts = urlparse(target_url)
message = data.encode("utf-8")
signature = signature_for_payload(message, secret)
- scheme_matrix: Dict[WebhookSchemes, Callable] = {
+ scheme_matrix: dict[WebhookSchemes, Callable] = {
WebhookSchemes.HTTP: send_webhook_using_http,
WebhookSchemes.HTTPS: send_webhook_using_http,
WebhookSchemes.AWS_SQS: send_webhook_using_aws_sqs,
@@ -282,7 +282,7 @@ def send_webhook_using_scheme_method(
event_type,
custom_headers=custom_headers,
)
- raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
+ raise ValueError(f"Unknown webhook scheme: {parts.scheme!r}")
def handle_webhook_retry(
@@ -599,8 +599,8 @@ def to_payment_app_id(app: "App", external_id: str) -> "str":
def parse_list_payment_gateways_response(
response_data: Any, app: "App"
-) -> List["PaymentGateway"]:
- gateways: List[PaymentGateway] = []
+) -> list["PaymentGateway"]:
+ gateways: list[PaymentGateway] = []
if not isinstance(response_data, list):
return gateways
diff --git a/saleor/webhook/validators.py b/saleor/webhook/validators.py
index 7a616ff5de..d9ffbfcacd 100644
--- a/saleor/webhook/validators.py
+++ b/saleor/webhook/validators.py
@@ -1,5 +1,3 @@
-from typing import Dict
-
from django.core.exceptions import ValidationError
HEADERS_NUMBER_LIMIT = 5
@@ -14,7 +12,7 @@ VALUE_CHARS_ALLOWED = (
)
-def custom_headers_validator(headers: Dict[str, str]) -> Dict[str, str]:
+def custom_headers_validator(headers: dict[str, str]) -> dict[str, str]:
"""Validate headers in accordance with RFC5322.
https://www.rfc-editor.org/rfc/rfc5322#section-2.2