From 56a3ebf86bd9a2c8729f7a32dad79104f67c1a37 Mon Sep 17 00:00:00 2001 From: Daniil Maltsev Date: Thu, 3 Jul 2025 12:12:25 +0500 Subject: [PATCH 1/2] More precise typing for BaseService --- {{ cookiecutter.name }}/src/app/services.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/{{ cookiecutter.name }}/src/app/services.py b/{{ cookiecutter.name }}/src/app/services.py index ee31547f..15ac18c5 100644 --- a/{{ cookiecutter.name }}/src/app/services.py +++ b/{{ cookiecutter.name }}/src/app/services.py @@ -1,9 +1,8 @@ from abc import ABCMeta, abstractmethod from collections.abc import Callable -from typing import Any -class BaseService(metaclass=ABCMeta): +class BaseService[T](metaclass=ABCMeta): """This is a template of a a base service. All services in the app should follow this rules: * Input variables should be done at the __init__ phase @@ -11,9 +10,9 @@ class BaseService(metaclass=ABCMeta): This is ok: @dataclass - class UserCreator(BaseService): + class UserCreator(BaseService[User]): first_name: str - last_name: Optional[str] + last_name: str | None def act(self) -> User: return User.objects.create(first_name=self.first_name, last_name=self.last_name) @@ -22,13 +21,13 @@ def act(self) -> User: This is not ok: class UserCreator: - def __call__(self, first_name: str, last_name: Optional[str]) -> User: + def __call__(self, first_name: str, last_name: str | None) -> User: return User.objects.create(first_name=self.first_name, last_name=self.last_name) For more implementation examples, check out https://github.com/tough-dev-school/education-backend/blob/master/src/apps/orders/services/order_course_changer.py """ - def __call__(self) -> Any: + def __call__(self) -> T: self.validate() return self.act() @@ -41,5 +40,5 @@ def validate(self) -> None: validator() @abstractmethod - def act(self) -> Any: + def act(self) -> T: raise NotImplementedError("Please implement in the service class") From 0edb3779100ef1b16f730bf21997265194fa1aef Mon Sep 17 00:00:00 2001 From: Daniil Maltsev Date: Thu, 3 Jul 2025 12:17:55 +0500 Subject: [PATCH 2/2] less code --- {{ cookiecutter.name }}/src/app/services.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/{{ cookiecutter.name }}/src/app/services.py b/{{ cookiecutter.name }}/src/app/services.py index 15ac18c5..0ac8b889 100644 --- a/{{ cookiecutter.name }}/src/app/services.py +++ b/{{ cookiecutter.name }}/src/app/services.py @@ -40,5 +40,4 @@ def validate(self) -> None: validator() @abstractmethod - def act(self) -> T: - raise NotImplementedError("Please implement in the service class") + def act(self) -> T: ...