explicit-python 2.5.0__tar.gz → 3.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {explicit_python-2.5.0/src/explicit_python.egg-info → explicit_python-3.1.0}/PKG-INFO +10 -9
  2. {explicit_python-2.5.0 → explicit_python-3.1.0}/README.md +5 -5
  3. {explicit_python-2.5.0 → explicit_python-3.1.0}/pyproject.toml +52 -16
  4. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/adapters/db.py +8 -5
  5. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/adapters/fs.py +4 -2
  6. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/adapters/messaging.py +5 -3
  7. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/contrib/domain/model/__init__.py +5 -2
  8. explicit_python-3.1.0/src/explicit/contrib/domain/model/fields.py +32 -0
  9. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/contrib/messagebus/event_registry.py +19 -13
  10. explicit_python-3.1.0/src/explicit/domain/__init__.py +54 -0
  11. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/domain/factories.py +8 -8
  12. explicit_python-3.1.0/src/explicit/domain/fields.py +67 -0
  13. explicit_python-3.1.0/src/explicit/domain/model.py +160 -0
  14. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/domain/types.py +17 -13
  15. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/domain/validation/exceptions.py +31 -20
  16. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/messagebus/__init__.py +3 -1
  17. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/messagebus/commands.py +24 -34
  18. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/messagebus/dependency_injection.py +13 -13
  19. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/messagebus/events.py +47 -47
  20. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/messagebus/exceptions.py +3 -1
  21. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/messagebus/messagebus.py +24 -15
  22. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/messagebus/queries.py +15 -16
  23. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/unit_of_work.py +15 -25
  24. {explicit_python-2.5.0 → explicit_python-3.1.0/src/explicit_python.egg-info}/PKG-INFO +10 -9
  25. explicit_python-3.1.0/src/explicit_python.egg-info/requires.txt +2 -0
  26. explicit_python-2.5.0/src/explicit/contrib/domain/model/fields.py +0 -31
  27. explicit_python-2.5.0/src/explicit/domain/__init__.py +0 -28
  28. explicit_python-2.5.0/src/explicit/domain/fields.py +0 -9
  29. explicit_python-2.5.0/src/explicit/domain/model.py +0 -152
  30. explicit_python-2.5.0/src/explicit_python.egg-info/requires.txt +0 -2
  31. {explicit_python-2.5.0 → explicit_python-3.1.0}/LICENSE +0 -0
  32. {explicit_python-2.5.0 → explicit_python-3.1.0}/MANIFEST.in +0 -0
  33. {explicit_python-2.5.0 → explicit_python-3.1.0}/setup.cfg +0 -0
  34. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/adapters/__init__.py +0 -0
  35. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/contrib/__init__.py +0 -0
  36. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/contrib/domain/__init__.py +0 -0
  37. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/contrib/messagebus/__init__.py +0 -0
  38. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/domain/validation/__init__.py +0 -0
  39. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit/py.typed +0 -0
  40. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit_python.egg-info/SOURCES.txt +0 -0
  41. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit_python.egg-info/dependency_links.txt +0 -0
  42. {explicit_python-2.5.0 → explicit_python-3.1.0}/src/explicit_python.egg-info/top_level.txt +0 -0
  43. {explicit_python-2.5.0 → explicit_python-3.1.0}/version.conf +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: explicit-python
3
- Version: 2.5.0
3
+ Version: 3.1.0
4
4
  Summary: Набор компонентов для построения многослойной архитектуры
5
5
  Author-email: BARS Group <bars@bars-open.ru>
6
6
  Project-URL: Homepage, https://stash.bars-open.ru/projects/EDUBASE/repos/explicit/browse
@@ -13,16 +13,17 @@ Classifier: Operating System :: OS Independent
13
13
  Classifier: License :: OSI Approved :: MIT License
14
14
  Classifier: Development Status :: 5 - Production/Stable
15
15
  Classifier: Programming Language :: Python
16
- Classifier: Programming Language :: Python :: 3.9
17
16
  Classifier: Programming Language :: Python :: 3.10
18
17
  Classifier: Programming Language :: Python :: 3.11
19
18
  Classifier: Programming Language :: Python :: 3.12
20
19
  Classifier: Programming Language :: Python :: 3.13
21
- Requires-Python: >=3.9
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Requires-Python: >=3.10
22
23
  Description-Content-Type: text/markdown
23
24
  License-File: LICENSE
24
25
  Requires-Dist: more_itertools
25
- Requires-Dist: pydantic<2.0
26
+ Requires-Dist: pydantic<3,>=2.14
26
27
  Dynamic: license-file
27
28
 
28
29
  # Explicit
@@ -176,7 +177,7 @@ def update_person(person, data: 'PersonDTO'):
176
177
  ```python
177
178
  class CommandBusMixin(ABC):
178
179
 
179
- _command_handlers: Dict[Type[Command], Callable] = {}
180
+ _command_handlers: dict[type[Command], Callable] = {}
180
181
 
181
182
  def handle_command(self, command: Command):
182
183
  """Передача запроса обработчику типа данного запроса."""
@@ -191,10 +192,10 @@ def update_person(person, data: 'PersonDTO'):
191
192
  ) -> 'Student':
192
193
  with uow.wrap():
193
194
  student: Student = domain_register_student(
194
- StudentDTO(**command.dict())
195
+ StudentDTO(**command.model_dump())
195
196
  )
196
197
  uow.add_event(events.StudentCreated(
197
- **command.dict(), **asdict(student)
198
+ **command.model_dump(), **asdict(student)
198
199
  ))
199
200
  return student
200
201
  ```
@@ -206,7 +207,7 @@ def update_person(person, data: 'PersonDTO'):
206
207
  ```python
207
208
  class EventBusMixin(ABC):
208
209
 
209
- _event_handlers: Dict[Type[Event], List[EventHandler]] = {}
210
+ _event_handlers: dict[type[Event], list[EventHandler]] = {}
210
211
 
211
212
  def handle_event(self, event: Event):
212
213
  """Передача события списку обработчиков типа данного события."""
@@ -275,7 +276,7 @@ def update_person(person, data: 'PersonDTO'):
275
276
  uow.students.update(student)
276
277
 
277
278
  uow.add_event(events.StudentCreated(
278
- **command.dict(), **asdict(student)
279
+ **command.model_dump(), **asdict(student)
279
280
  ))
280
281
  ```
281
282
 
@@ -149,7 +149,7 @@ def update_person(person, data: 'PersonDTO'):
149
149
  ```python
150
150
  class CommandBusMixin(ABC):
151
151
 
152
- _command_handlers: Dict[Type[Command], Callable] = {}
152
+ _command_handlers: dict[type[Command], Callable] = {}
153
153
 
154
154
  def handle_command(self, command: Command):
155
155
  """Передача запроса обработчику типа данного запроса."""
@@ -164,10 +164,10 @@ def update_person(person, data: 'PersonDTO'):
164
164
  ) -> 'Student':
165
165
  with uow.wrap():
166
166
  student: Student = domain_register_student(
167
- StudentDTO(**command.dict())
167
+ StudentDTO(**command.model_dump())
168
168
  )
169
169
  uow.add_event(events.StudentCreated(
170
- **command.dict(), **asdict(student)
170
+ **command.model_dump(), **asdict(student)
171
171
  ))
172
172
  return student
173
173
  ```
@@ -179,7 +179,7 @@ def update_person(person, data: 'PersonDTO'):
179
179
  ```python
180
180
  class EventBusMixin(ABC):
181
181
 
182
- _event_handlers: Dict[Type[Event], List[EventHandler]] = {}
182
+ _event_handlers: dict[type[Event], list[EventHandler]] = {}
183
183
 
184
184
  def handle_event(self, event: Event):
185
185
  """Передача события списку обработчиков типа данного события."""
@@ -248,7 +248,7 @@ def update_person(person, data: 'PersonDTO'):
248
248
  uow.students.update(student)
249
249
 
250
250
  uow.add_event(events.StudentCreated(
251
- **command.dict(), **asdict(student)
251
+ **command.model_dump(), **asdict(student)
252
252
  ))
253
253
  ```
254
254
 
@@ -15,7 +15,7 @@ license-files = ['LICENSE']
15
15
  authors = [
16
16
  {name = 'BARS Group', email = 'bars@bars-open.ru'}
17
17
  ]
18
- requires-python = '>=3.9'
18
+ requires-python = '>=3.10'
19
19
  classifiers = [
20
20
  'Intended Audience :: Developers',
21
21
  'Environment :: Web Environment',
@@ -25,15 +25,16 @@ classifiers = [
25
25
  'License :: OSI Approved :: MIT License',
26
26
  'Development Status :: 5 - Production/Stable',
27
27
  'Programming Language :: Python',
28
- 'Programming Language :: Python :: 3.9',
29
28
  'Programming Language :: Python :: 3.10',
30
29
  'Programming Language :: Python :: 3.11',
31
30
  'Programming Language :: Python :: 3.12',
32
31
  'Programming Language :: Python :: 3.13',
32
+ 'Programming Language :: Python :: 3.14',
33
+ 'Programming Language :: Python :: 3.15',
33
34
  ]
34
35
  dependencies = [
35
36
  'more_itertools',
36
- 'pydantic<2.0',
37
+ 'pydantic>=2.14,<3',
37
38
  ]
38
39
  dynamic = ['version']
39
40
 
@@ -59,23 +60,17 @@ no_site_packages = true
59
60
  ignore_missing_imports = true
60
61
 
61
62
  [tool.isort]
63
+ multi_line_output = 3
64
+ force_grid_wrap = 1
65
+ include_trailing_comma = true
62
66
  line_length = 120
63
- force_single_line = true
64
- indent = 4
65
- atomic = true
66
- from_first = true
67
+ combine_as_imports = true
67
68
  lines_after_imports = 2
68
- use_parentheses = true
69
- extra_standard_library = [
70
- 'dataclasses',
71
- ]
72
- known_project=[
69
+ known_project = [
73
70
  'explicit',
74
- 'echo',
75
- 'edu',
76
- 'training',
71
+ 'testapp',
77
72
  ]
78
- sections=[
73
+ sections = [
79
74
  'FUTURE',
80
75
  'STDLIB',
81
76
  'THIRDPARTY',
@@ -83,3 +78,44 @@ sections=[
83
78
  'PROJECT',
84
79
  'LOCALFOLDER',
85
80
  ]
81
+
82
+ [tool.ruff]
83
+ target-version = 'py310'
84
+ line-length = 120
85
+ indent-width = 4
86
+
87
+ [tool.ruff.lint]
88
+ select = ['F', 'E', 'D', 'W', 'S', 'N', 'UP007', 'UP045']
89
+ ignore = [
90
+ # Missing docstring in public module
91
+ 'D100',
92
+ # Missing docstring in public class
93
+ 'D101',
94
+ # Missing docstring in public method
95
+ 'D102',
96
+ # Missing docstring in public function
97
+ 'D103',
98
+ # Missing docstring in public package
99
+ 'D104',
100
+ # Missing docstring in magic method
101
+ 'D105',
102
+ # Missing docstring in public nested class
103
+ 'D106',
104
+ # Missing docstring in __init__
105
+ 'D107',
106
+ # use of assert detected (useless with pytest)
107
+ 'S101',
108
+ ]
109
+
110
+ [tool.ruff.lint.pydocstyle]
111
+ convention = 'google'
112
+
113
+ [tool.ruff.format]
114
+ quote-style = 'single'
115
+ indent-style = 'space'
116
+ docstring-code-format = true
117
+
118
+ [tool.ruff.lint.per-file-ignores]
119
+ '*/tests/*' = ['D', 'S106']
120
+ '**/__init__.py' = ['F401']
121
+ '**/domain/model.py' = ['N818']
@@ -1,11 +1,15 @@
1
1
  """Абстракции адаптера СУБД."""
2
- from abc import ABCMeta
3
- from abc import abstractmethod
4
- from typing import Any
5
2
 
3
+ from abc import (
4
+ ABCMeta,
5
+ abstractmethod,
6
+ )
7
+ from typing import (
8
+ Any,
9
+ )
6
10
 
7
- class AbstractSpecification(metaclass=ABCMeta):
8
11
 
12
+ class AbstractSpecification(metaclass=ABCMeta):
9
13
  """Набор условий для проверки соответствия объекта этим условиям."""
10
14
 
11
15
  @abstractmethod
@@ -18,7 +22,6 @@ class AbstractSpecification(metaclass=ABCMeta):
18
22
 
19
23
 
20
24
  class AbstractRepository(metaclass=ABCMeta):
21
-
22
25
  """Репозиторий - абстракция над хранилищем данных (БД).
23
26
 
24
27
  Должен содержать методы получения объектов со всеми вариантами выборки:
@@ -1,9 +1,11 @@
1
1
  """Абстракции адаптера к хранилищу файлов."""
2
- from abc import ABC
3
2
 
3
+ from abc import (
4
+ ABC,
5
+ )
4
6
 
5
- class AbstractAdapter(ABC):
6
7
 
8
+ class AbstractAdapter(ABC):
7
9
  """Абстрактный адаптер к хранилищу файлов.
8
10
 
9
11
  .. code-block:: python
@@ -1,10 +1,12 @@
1
1
  """Абстракции адаптера обмена сообщениями."""
2
- from abc import ABC
3
- from abc import abstractmethod
4
2
 
3
+ from abc import (
4
+ ABC,
5
+ abstractmethod,
6
+ )
5
7
 
6
- class AbstractAdapter(ABC):
7
8
 
9
+ class AbstractAdapter(ABC):
8
10
  @abstractmethod
9
11
  def publish(self, message, *args, **kwargs):
10
12
  raise NotImplementedError()
@@ -1,6 +1,9 @@
1
1
  """Дополнения для моделей предметной области."""
2
- from .fields import identifier
3
- from .fields import uuid_identifier
2
+
3
+ from .fields import (
4
+ identifier,
5
+ uuid_identifier,
6
+ )
4
7
 
5
8
 
6
9
  __all__ = [
@@ -0,0 +1,32 @@
1
+ """Поля модели предметной области."""
2
+
3
+ from uuid import (
4
+ uuid4,
5
+ )
6
+
7
+ from pydantic.fields import (
8
+ Field,
9
+ )
10
+
11
+
12
+ def identifier(**kwargs):
13
+ return Field(
14
+ None,
15
+ title='Идентификатор',
16
+ description=(
17
+ 'Идентификатор записи. Может отсутствовать у создаваемых объектов, но обязан присутствовать у существующих.'
18
+ ),
19
+ gt=0,
20
+ **kwargs,
21
+ )
22
+
23
+
24
+ def uuid_identifier(**kwargs):
25
+ return Field(
26
+ default_factory=uuid4,
27
+ title='Идентификатор UUID',
28
+ description=(
29
+ 'Идентификатор записи. Может отсутствовать у создаваемых объектов, но обязан присутствовать у существующих.'
30
+ ),
31
+ **kwargs,
32
+ )
@@ -1,15 +1,21 @@
1
1
  """Реестр событий по топикам."""
2
- from collections import defaultdict
3
- from dataclasses import dataclass
4
- from typing import TYPE_CHECKING
5
- from typing import Dict
6
- from typing import Type
7
- from typing import Union
2
+
8
3
  import logging
4
+ from collections import (
5
+ defaultdict,
6
+ )
7
+ from dataclasses import (
8
+ dataclass,
9
+ )
10
+ from typing import (
11
+ TYPE_CHECKING,
12
+ )
9
13
 
10
14
 
11
15
  if TYPE_CHECKING:
12
- from explicit.messagebus.events import Event
16
+ from explicit.messagebus.events import (
17
+ Event,
18
+ )
13
19
 
14
20
  logger = logging.getLogger(__name__)
15
21
  logger.setLevel(logging.INFO)
@@ -28,21 +34,21 @@ class Message:
28
34
 
29
35
 
30
36
  class Registry:
31
-
32
37
  """Реестр событий по топикам."""
33
38
 
34
- _registry: Dict[str, list[Type['Event']]]
39
+ _registry: dict[str, list[type['Event']]]
35
40
 
36
41
  def __init__(self):
37
42
  self._registry = defaultdict(list)
38
43
 
39
- def register(self, topic: str, *events: Type['Event']) -> None:
44
+ def register(self, topic: str, *events: type['Event']) -> None:
40
45
  """Регистрирует сопоставление топика с типом события."""
41
46
  self._registry[topic].extend(events)
42
47
 
43
- def resolve(self, message: Message) -> Union['Event', None]:
44
- """
45
- Определяет подходящий тип события и возвращает экземпляр для передачи на обработку в шину событий либо None.
48
+ def resolve(self, message: Message) -> 'Event | None':
49
+ """Определяет подходящий тип события.
50
+
51
+ Возвращает экземпляр для передачи на обработку в шину событий либо None.
46
52
  """
47
53
  event = None
48
54
 
@@ -0,0 +1,54 @@
1
+ """Объекты предметной области."""
2
+
3
+ from .factories import (
4
+ AbstractDomainFactory,
5
+ DTOBase,
6
+ )
7
+ from .fields import (
8
+ Field,
9
+ get_field_attribute,
10
+ get_field_title,
11
+ )
12
+ from .model import (
13
+ HasUnsetValues,
14
+ Unset,
15
+ asdict,
16
+ is_unset,
17
+ unset,
18
+ )
19
+ from .types import (
20
+ Bool,
21
+ Date,
22
+ Int,
23
+ NoneBool,
24
+ NoneDate,
25
+ NoneInt,
26
+ NoneStr,
27
+ NoneUnsetUUID,
28
+ Str,
29
+ UnsetUUID,
30
+ )
31
+
32
+
33
+ __all__ = [
34
+ 'AbstractDomainFactory',
35
+ 'DTOBase',
36
+ 'Unset',
37
+ 'unset',
38
+ 'is_unset',
39
+ 'HasUnsetValues',
40
+ 'asdict',
41
+ 'Field',
42
+ 'get_field_title',
43
+ 'get_field_attribute',
44
+ 'UnsetUUID',
45
+ 'Bool',
46
+ 'Date',
47
+ 'Int',
48
+ 'NoneBool',
49
+ 'NoneDate',
50
+ 'NoneInt',
51
+ 'NoneStr',
52
+ 'NoneUnsetUUID',
53
+ 'Str',
54
+ ]
@@ -1,14 +1,18 @@
1
1
  """Объекты передачи данных."""
2
- from abc import ABCMeta
3
- from abc import abstractmethod
2
+
3
+ from abc import (
4
+ ABCMeta,
5
+ abstractmethod,
6
+ )
4
7
 
5
8
  from pydantic.main import BaseModel # pylint: disable=no-name-in-module
6
9
 
7
- from .model import HasUnsetValues
10
+ from .model import (
11
+ HasUnsetValues,
12
+ )
8
13
 
9
14
 
10
15
  class DTOBase(HasUnsetValues, BaseModel):
11
-
12
16
  """Базовый объект передачи данных.
13
17
 
14
18
  .. code-block::python
@@ -18,12 +22,8 @@ class DTOBase(HasUnsetValues, BaseModel):
18
22
 
19
23
  """
20
24
 
21
- class Config:
22
- arbitrary_types_allowed = False
23
-
24
25
 
25
26
  class AbstractDomainFactory(metaclass=ABCMeta):
26
-
27
27
  @abstractmethod
28
28
  def create(self, data):
29
29
  """Сборка объекта модели предметной области из переданных данных.
@@ -0,0 +1,67 @@
1
+ """Набор полей объектов предметной области."""
2
+
3
+ from functools import (
4
+ partial,
5
+ )
6
+ from typing import (
7
+ Any,
8
+ )
9
+
10
+ from pydantic import (
11
+ Field as DefaultField,
12
+ )
13
+
14
+ from .model import (
15
+ unset,
16
+ )
17
+
18
+
19
+ Field = partial(DefaultField, default=unset) # pylint: disable=invalid-name
20
+
21
+
22
+ def get_field_title(cls: type, name: str) -> str:
23
+ """Возвращает заголовок поля pydantic-модели или pydantic-датакласса.
24
+
25
+ Если заголовок не задан, возвращает имя поля.
26
+
27
+ .. code-block:: python
28
+
29
+ @dataclass
30
+ class User:
31
+ username: str = Field(title='Логин')
32
+ email: str
33
+
34
+
35
+ get_field_title(User, 'username') == 'Логин'
36
+ get_field_title(User, 'email') == 'email'
37
+
38
+ """
39
+ return cls.__pydantic_fields__[name].title or name # type: ignore[attr-defined]
40
+
41
+
42
+ def get_field_attribute(cls: type, name: str, attribute: str) -> Any:
43
+ """Возвращает атрибут поля pydantic-модели или pydantic-датакласса.
44
+
45
+ Ограничения (``max_length``, ``ge``, ``max_digits`` и т.п.) pydantic хранит не в самом поле,
46
+ а в его метаданных, поэтому атрибут ищется и там.
47
+
48
+ .. code-block:: python
49
+
50
+ @dataclass
51
+ class User:
52
+ username: str = Field(title='Логин', max_length=50)
53
+
54
+
55
+ get_field_attribute(User, 'username', 'max_length') == 50
56
+
57
+ Raises:
58
+ AttributeError: если атрибут у поля не задан.
59
+
60
+ """
61
+ field = cls.__pydantic_fields__[name] # type: ignore[attr-defined]
62
+ if (value := getattr(field, attribute, None)) is not None:
63
+ return value
64
+ for meta in field.metadata:
65
+ if (value := getattr(meta, attribute, None)) is not None:
66
+ return value
67
+ raise AttributeError(f'У поля {cls.__name__}.{name} не задан атрибут {attribute}')
@@ -0,0 +1,160 @@
1
+ """Вспомогательные утилиты и типы предметной области."""
2
+
3
+ from typing import (
4
+ TYPE_CHECKING,
5
+ Any,
6
+ ClassVar,
7
+ Generic,
8
+ Protocol,
9
+ TypeVar,
10
+ )
11
+
12
+ from pydantic import (
13
+ ConfigDict,
14
+ GetCoreSchemaHandler,
15
+ SerializerFunctionWrapHandler,
16
+ TypeAdapter,
17
+ model_serializer,
18
+ )
19
+ from pydantic.main import (
20
+ BaseModel,
21
+ )
22
+ from pydantic_core import (
23
+ CoreSchema,
24
+ core_schema,
25
+ )
26
+
27
+
28
+ if TYPE_CHECKING:
29
+ from pydantic.main import (
30
+ IncEx,
31
+ )
32
+
33
+
34
+ class __IsDataclass(Protocol): # pylint: disable=invalid-name
35
+ """Протокол датакласса.
36
+
37
+ Лучший из известных способов сделать соответствующую подсказку.
38
+ """
39
+
40
+ __dataclass_fields__: ClassVar[dict]
41
+
42
+
43
+ T = TypeVar('T')
44
+
45
+
46
+ class __SingletonMeta(type, Generic[T]): # pylint: disable=invalid-name
47
+ _instances: 'dict[__SingletonMeta[T], T]' = {} # pylint: disable=invalid-sequence-index
48
+
49
+ def __call__(cls: '__SingletonMeta', *args, **kwargs):
50
+ if cls not in cls._instances:
51
+ cls._instances[cls] = super().__call__(*args, **kwargs)
52
+ return cls._instances[cls]
53
+
54
+
55
+ class Unset(metaclass=__SingletonMeta):
56
+ """Sentinel type.
57
+
58
+ Обозначает отсутствие значения, в т.ч. None.
59
+ """
60
+
61
+ def __bool__(self):
62
+ """Проверка на истинность.
63
+
64
+ Всегда возвращает False, т.к. обозначает отсутствующее значение.
65
+
66
+ Например:
67
+
68
+ class Model:
69
+ some_attr = unset
70
+
71
+ if Model().some_attr:
72
+ print('Model has some_attr')
73
+
74
+ """
75
+ return False
76
+
77
+ def __repr__(self):
78
+ return '<unset>'
79
+
80
+ def __reduce__(self):
81
+ """Сериализация экземпляра.
82
+
83
+ Возвращает имя глобальной переменной модуля, поэтому copy, deepcopy
84
+ и pickle возвращают тот же экземпляр, а не его копию.
85
+
86
+ Например:
87
+
88
+ assert deepcopy(unset) is unset
89
+ assert pickle.loads(pickle.dumps(unset)) is unset
90
+
91
+ """
92
+ return 'unset'
93
+
94
+ @classmethod
95
+ def __get_pydantic_core_schema__( # pylint: disable=unused-argument
96
+ cls, source_type: Any, handler: GetCoreSchemaHandler
97
+ ) -> CoreSchema:
98
+ return core_schema.is_instance_schema(cls)
99
+
100
+
101
+ unset = Unset() # Sentinel value
102
+
103
+
104
+ def is_unset(obj) -> bool:
105
+ return isinstance(obj, Unset)
106
+
107
+
108
+ class HasUnsetValues(BaseModel):
109
+ """Примесь к моделям, значения которых могут быть не заданы."""
110
+
111
+ # Вложенные модели сериализуются по фактическому типу, а не по объявленному в аннотации поля.
112
+ model_config = ConfigDict(polymorphic_serialization=True)
113
+
114
+ @model_serializer(mode='wrap')
115
+ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
116
+ """Отбрасывает не установленные значения при сериализации, в т.ч. во вложенных моделях.
117
+
118
+ .. code-block:: python
119
+
120
+ class DocumentDTO(DTOBase):
121
+ series = unset
122
+ number = unser
123
+
124
+
125
+ DocumentDTO(number='1').model_dump() == {'number': '1'}
126
+
127
+ """
128
+ return {k: v for k, v in handler(self).items() if not is_unset(v)}
129
+
130
+
131
+ def filter_unset(d: Any):
132
+ if not isinstance(d, dict):
133
+ return d
134
+
135
+ return dict((k, filter_unset(v)) for k, v in d.items() if not is_unset(v))
136
+
137
+
138
+ # Разворачивает в словари модели и датаклассы на любом уровне вложенности, в т.ч. модели внутри датаклассов.
139
+ _any_adapter = TypeAdapter(Any)
140
+
141
+
142
+ def asdict(
143
+ obj: __IsDataclass | HasUnsetValues,
144
+ include: 'IncEx | None' = None,
145
+ exclude: 'IncEx | None' = None,
146
+ ) -> dict:
147
+ """Формирует словарь из данных объекта, отбрасывая не установленные значения.
148
+
149
+ .. code-block:: python
150
+
151
+ @dataclass
152
+ class Document:
153
+ series = unset
154
+ number = unser
155
+
156
+
157
+ asdict(Document(number='1')) == {'number': '1'}
158
+
159
+ """
160
+ return filter_unset(_any_adapter.dump_python(obj, include=include, exclude=exclude))