attack-on-domain 0.0.1__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 (30) hide show
  1. attack_on_domain-0.0.1/LICENSE +201 -0
  2. attack_on_domain-0.0.1/PKG-INFO +61 -0
  3. attack_on_domain-0.0.1/README.md +37 -0
  4. attack_on_domain-0.0.1/code/aod/__init__.py +21 -0
  5. attack_on_domain-0.0.1/code/aod/_internal/__init__.py +1 -0
  6. attack_on_domain-0.0.1/code/aod/_internal/core/__init__.py +0 -0
  7. attack_on_domain-0.0.1/code/aod/_internal/core/__main__.py +64 -0
  8. attack_on_domain-0.0.1/code/aod/_internal/core/base_inmutable.py +17 -0
  9. attack_on_domain-0.0.1/code/aod/_internal/core/base_mutable.py +117 -0
  10. attack_on_domain-0.0.1/code/aod/_internal/core/base_validator.py +60 -0
  11. attack_on_domain-0.0.1/code/aod/_internal/core/domain_exception.py +41 -0
  12. attack_on_domain-0.0.1/code/aod/_internal/core/event_emitter.py +23 -0
  13. attack_on_domain-0.0.1/code/aod/_internal/core/fields/__init__.py +3 -0
  14. attack_on_domain-0.0.1/code/aod/_internal/core/fields/fields.py +94 -0
  15. attack_on_domain-0.0.1/code/aod/_internal/core/model_maker.py +75 -0
  16. attack_on_domain-0.0.1/code/aod/_internal/core/validators/__init__.py +15 -0
  17. attack_on_domain-0.0.1/code/aod/_internal/core/validators/validators.py +59 -0
  18. attack_on_domain-0.0.1/code/aod/_internal/domain/__init__.py +6 -0
  19. attack_on_domain-0.0.1/code/aod/_internal/domain/bounded_context.py +53 -0
  20. attack_on_domain-0.0.1/code/aod/_internal/domain/entity.py +51 -0
  21. attack_on_domain-0.0.1/code/aod/_internal/domain/service.py +3 -0
  22. attack_on_domain-0.0.1/code/aod/_internal/domain/value_object.py +22 -0
  23. attack_on_domain-0.0.1/code/aod/py.typed +0 -0
  24. attack_on_domain-0.0.1/code/attack_on_domain.egg-info/PKG-INFO +61 -0
  25. attack_on_domain-0.0.1/code/attack_on_domain.egg-info/SOURCES.txt +28 -0
  26. attack_on_domain-0.0.1/code/attack_on_domain.egg-info/dependency_links.txt +1 -0
  27. attack_on_domain-0.0.1/code/attack_on_domain.egg-info/requires.txt +2 -0
  28. attack_on_domain-0.0.1/code/attack_on_domain.egg-info/top_level.txt +1 -0
  29. attack_on_domain-0.0.1/pyproject.toml +64 -0
  30. attack_on_domain-0.0.1/setup.cfg +4 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: attack-on-domain
3
+ Version: 0.0.1
4
+ Summary: DDD building blocks: entities, value objects, bounded contexts, and validation helpers.
5
+ Author: Alfonso Cuesta
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/AlfonsoCuesta/attack-on-domain
8
+ Project-URL: Repository, https://github.com/AlfonsoCuesta/attack-on-domain
9
+ Project-URL: Issues, https://github.com/AlfonsoCuesta/attack-on-domain/issues
10
+ Keywords: ddd,domain-driven-design,entity,value-object
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.14
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: pydantic>=2.12.4
22
+ Requires-Dist: typing-inspect>=0.9.0
23
+ Dynamic: license-file
24
+
25
+ # attack-on-domain
26
+
27
+ Helpers for **domain-driven design** in Python: entities, value objects, bounded contexts, domain events, and Pydantic v2–based validation.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install attack-on-domain
33
+ ```
34
+
35
+ With **uv** in another project:
36
+
37
+ ```bash
38
+ uv add attack-on-domain
39
+ ```
40
+
41
+ Or install into the active environment:
42
+
43
+ ```bash
44
+ uv pip install attack-on-domain
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ Import only from the top-level package:
50
+
51
+ ```python
52
+ from aod import (
53
+ BoundedContext,
54
+ DomainEvent,
55
+ DomainException,
56
+ Entity,
57
+ ValueObject,
58
+ )
59
+ ```
60
+
61
+ Requires **Python 3.14+**.
@@ -0,0 +1,37 @@
1
+ # attack-on-domain
2
+
3
+ Helpers for **domain-driven design** in Python: entities, value objects, bounded contexts, domain events, and Pydantic v2–based validation.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install attack-on-domain
9
+ ```
10
+
11
+ With **uv** in another project:
12
+
13
+ ```bash
14
+ uv add attack-on-domain
15
+ ```
16
+
17
+ Or install into the active environment:
18
+
19
+ ```bash
20
+ uv pip install attack-on-domain
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ Import only from the top-level package:
26
+
27
+ ```python
28
+ from aod import (
29
+ BoundedContext,
30
+ DomainEvent,
31
+ DomainException,
32
+ Entity,
33
+ ValueObject,
34
+ )
35
+ ```
36
+
37
+ Requires **Python 3.14+**.
@@ -0,0 +1,21 @@
1
+ """
2
+ Public API for the aod library.
3
+
4
+ Supported imports: ``from aod import …`` only. The ``_internal`` package
5
+ exists for packaging layout only; it is not a semver-stable API surface.
6
+ """
7
+
8
+ from aod._internal.core.domain_exception import DomainException
9
+ from aod._internal.core.event_emitter import Event as DomainEvent
10
+ from aod._internal.domain.bounded_context import BoundedContext
11
+ from aod._internal.domain.entity import Entity, RootEntity
12
+ from aod._internal.domain.value_object import ValueObject
13
+
14
+ __all__ = [
15
+ "BoundedContext",
16
+ "DomainEvent",
17
+ "DomainException",
18
+ "Entity",
19
+ "RootEntity",
20
+ "ValueObject",
21
+ ]
@@ -0,0 +1 @@
1
+ """Implementation modules; not part of the supported public API."""
@@ -0,0 +1,64 @@
1
+ from typing import Annotated, Any, Self
2
+
3
+ from .base_inmutable import BaseInmutable
4
+ from .base_mutable import BaseMutable
5
+ from .base_validator import BaseValidator
6
+ from .fields.fields import Field, PrivateField
7
+ from .validators import (
8
+ AfterValidator,
9
+ field_validator,
10
+ post_init,
11
+ )
12
+
13
+ print(BaseValidator)
14
+ print(BaseMutable)
15
+
16
+
17
+ def text(value: Any) -> str:
18
+ return "Hola"
19
+
20
+
21
+ def main() -> None:
22
+ class Prueba:
23
+ def __init__(self, a: int) -> None:
24
+ self.a = a
25
+
26
+ class User(BaseMutable):
27
+ age: int = 0
28
+ _prueba: int = PrivateField()
29
+
30
+ @field_validator("age")
31
+ def is_even(cls, value: int) -> int:
32
+ return 22
33
+
34
+ @post_init
35
+ def validate_age(self) -> Self:
36
+ return self
37
+
38
+ class User2(User):
39
+ a: int = Field()
40
+ text: Annotated[str, AfterValidator(text)]
41
+ prueba_attr: Prueba
42
+
43
+ def change_text(self, text: str) -> None:
44
+ self.text = text
45
+
46
+ def can_mutate(self) -> bool:
47
+ return self.text != "Adio"
48
+
49
+ def prueba(self) -> None:
50
+ print("prueba")
51
+
52
+ prueba = Prueba(a=1)
53
+ a = User2(text="Adio", age=2, a=1, prueba_attr=prueba)
54
+
55
+ class User3(BaseInmutable):
56
+ age: int = 0
57
+
58
+ user3 = User3(age=1)
59
+ print(user3)
60
+ user3.age = 2
61
+
62
+
63
+ if __name__ == "__main__":
64
+ main()
@@ -0,0 +1,17 @@
1
+ from typing import Any
2
+
3
+ from .base_validator import BaseValidator
4
+ from .domain_exception import MutationForbiddenError
5
+
6
+
7
+ class BaseInmutable(BaseValidator):
8
+ __initialized__: bool = False
9
+
10
+ def __setattr__(self, name: str, value: Any) -> None:
11
+ if self.__initialized__:
12
+ raise MutationForbiddenError()
13
+ super().__setattr__(name, value)
14
+
15
+ def __init__(self, **kwargs: Any) -> None:
16
+ super().__init__(**kwargs)
17
+ self.__initialized__ = True
@@ -0,0 +1,117 @@
1
+ import inspect
2
+ from contextlib import contextmanager
3
+ from enum import StrEnum
4
+ from functools import wraps
5
+ from typing import Any, Callable, Generator, Literal, Type, cast
6
+
7
+ from .base_validator import BaseValidator, PydanticFacadeMeta
8
+ from .domain_exception import MutationForbiddenError
9
+
10
+
11
+ class MutatingState(StrEnum):
12
+ BLOCK = "block"
13
+ PASS = "pass"
14
+ SUPER = "super"
15
+
16
+
17
+ class MutatingContext:
18
+ def __init__(self):
19
+ self._deep_states = {
20
+ MutatingState.PASS: 0,
21
+ MutatingState.SUPER: 0,
22
+ }
23
+
24
+ def enter(
25
+ self, state: Literal[MutatingState.PASS, MutatingState.SUPER]
26
+ ) -> None:
27
+ self._deep_states[state] += 1
28
+
29
+ def exit(
30
+ self, state: Literal[MutatingState.PASS, MutatingState.SUPER]
31
+ ) -> None:
32
+ self._deep_states[state] -= 1 if self._deep_states[state] > 0 else 0
33
+
34
+ @property
35
+ def status(
36
+ self,
37
+ ) -> Literal[MutatingState.BLOCK, MutatingState.PASS, MutatingState.SUPER]:
38
+ return (
39
+ MutatingState.SUPER
40
+ if self._deep_states[MutatingState.SUPER] > 0
41
+ else MutatingState.PASS
42
+ if self._deep_states[MutatingState.PASS] > 0
43
+ else MutatingState.BLOCK
44
+ )
45
+
46
+
47
+ class MutableBaseMeta(PydanticFacadeMeta):
48
+ NOT_MUTABLE_CALLABLES = {
49
+ "can_mutate",
50
+ "_get_mutating_context",
51
+ }
52
+
53
+ def __new__(mcls, name, bases, namespace):
54
+
55
+ cls = super().__new__(mcls, name, bases, namespace)
56
+
57
+ def mutate(fn: Callable) -> Callable:
58
+ @wraps(fn)
59
+ def wrapper(self: BaseMutable, *args: Any, **kwargs: Any) -> Any:
60
+ super_mutate = fn.__name__.startswith("_")
61
+ with self.__mutate__(super_mutate=super_mutate):
62
+ return fn(self, *args, **kwargs)
63
+
64
+ setattr(wrapper, "__mutable__", True)
65
+
66
+ return wrapper
67
+
68
+ for base in cls.__mro__:
69
+ for attr_name, attr_value in base.__dict__.items():
70
+ if attr_name.startswith("__") and attr_name.endswith("__"):
71
+ continue
72
+ if attr_name in cls.NOT_MUTABLE_CALLABLES or getattr(
73
+ attr_value, "__mutable__", False
74
+ ):
75
+ continue
76
+ if not inspect.isfunction(attr_value):
77
+ continue
78
+ setattr(cls, attr_name, mutate(attr_value))
79
+ return cls
80
+
81
+
82
+ class BaseMutable(BaseValidator, metaclass=MutableBaseMeta):
83
+ __mutating_context__: MutatingContext | None = None
84
+ __mutating_context_class__: Type[MutatingContext] = MutatingContext
85
+
86
+ def can_mutate(self) -> bool:
87
+ return True
88
+
89
+ def _get_mutating_context(self) -> MutatingContext:
90
+ if self.__mutating_context__ is None:
91
+ object.__setattr__(
92
+ self, "__mutating_context__", self.__mutating_context_class__()
93
+ )
94
+ return cast(MutatingContext, self.__mutating_context__)
95
+
96
+ @contextmanager
97
+ def __mutate__(
98
+ self, super_mutate: bool = False
99
+ ) -> Generator[None, None, None]:
100
+ mutating_context = self._get_mutating_context()
101
+ mutation: Literal[MutatingState.PASS, MutatingState.SUPER] = (
102
+ MutatingState.SUPER if super_mutate else MutatingState.PASS
103
+ )
104
+ mutating_context.enter(mutation)
105
+ yield
106
+ mutating_context.exit(mutation)
107
+
108
+ def __setattr__(self, name: str, value: Any) -> None:
109
+ mutating_status = self._get_mutating_context().status
110
+ super_mutate = mutating_status == MutatingState.SUPER
111
+ pass_mutate = (
112
+ mutating_status == MutatingState.PASS and self.can_mutate()
113
+ )
114
+ can_mutate = super_mutate or pass_mutate
115
+ if not can_mutate:
116
+ raise MutationForbiddenError()
117
+ super().__setattr__(name, value)
@@ -0,0 +1,60 @@
1
+ import inspect
2
+ from typing import Any, ClassVar, Self, Type, dataclass_transform
3
+
4
+ from pydantic import BaseModel
5
+
6
+ from .fields import Field
7
+ from .model_maker import (
8
+ RAW_MODEL_KEY,
9
+ VALIDATION_MODEL_KEY,
10
+ make_raw_model,
11
+ make_validation_model,
12
+ )
13
+
14
+
15
+ class PydanticFacadeMeta(type):
16
+ def __new__(mcls, name, bases, namespace):
17
+ cls = super().__new__(mcls, name, bases, namespace)
18
+
19
+ validation_model = make_validation_model(cls, name, bases)
20
+ raw_model = make_raw_model(cls, name, bases)
21
+
22
+ setattr(cls, VALIDATION_MODEL_KEY, validation_model)
23
+ setattr(cls, RAW_MODEL_KEY, raw_model)
24
+
25
+ cls.__init__.__signature__ = inspect.signature(validation_model)
26
+
27
+ return cls
28
+
29
+
30
+ @dataclass_transform(field_specifiers=(Field,), kw_only_default=True)
31
+ class BaseValidator(metaclass=PydanticFacadeMeta):
32
+ __validation_model__: ClassVar[Type[BaseModel]]
33
+ __raw_model__: ClassVar[Type[BaseModel]]
34
+
35
+ def __init__(self, **kwargs: Any) -> None:
36
+ model = self.__class__.__validation_model__
37
+ validated = model(**kwargs)
38
+
39
+ self._set_model_attributes(validated)
40
+
41
+ def _set_model_attributes(self, validated: BaseModel) -> None:
42
+ for k, v in validated.model_dump().items():
43
+ setattr(self, k, v)
44
+
45
+ private = getattr(validated, "__pydantic_private__", {})
46
+ if private:
47
+ for k, v in private.items():
48
+ setattr(self, k, v)
49
+
50
+ def __repr__(self):
51
+ fields = self.__validation_model__.model_fields.keys()
52
+ args = ", ".join(f"{k}={getattr(self, k)!r}" for k in fields)
53
+ return f"{self.__class__.__name__}({args})"
54
+
55
+ @classmethod
56
+ def from_existing(cls, **kwargs) -> Self:
57
+ object = cls.__raw_model__(**kwargs)
58
+ instance = cls.__new__(cls)
59
+ instance._set_model_attributes(object)
60
+ return instance
@@ -0,0 +1,41 @@
1
+ class DomainException(Exception):
2
+ """Base for errors raised by domain rules and related guards."""
3
+
4
+ pass
5
+
6
+
7
+ class MutationForbiddenError(DomainException):
8
+ """Raised when a mutable or immutable object is updated outside allowed context."""
9
+
10
+ def __init__(self, message: str = "Cannot mutate this object") -> None:
11
+ super().__init__(message)
12
+
13
+
14
+ class InvalidEntityTypeError(DomainException):
15
+ """Raised when a type registered as aggregate root is not an Entity subclass."""
16
+
17
+ def __init__(self, type_name: str) -> None:
18
+ super().__init__(f"{type_name} is not an Entity")
19
+
20
+
21
+ class InvalidRootEntityTypeError(DomainException):
22
+ """Raised when a type is an Entity but not declared as aggregate root."""
23
+
24
+ def __init__(self, type_name: str) -> None:
25
+ super().__init__(f"{type_name} is not a root Entity")
26
+
27
+
28
+ class InvalidServiceTypeError(DomainException):
29
+ """Raised when a type registered as service is not a Service subclass."""
30
+
31
+ def __init__(self, type_name: str) -> None:
32
+ super().__init__(f"{type_name} is not a Service")
33
+
34
+
35
+ class ClassExpectedError(DomainException):
36
+ """Raised when a class was required but a non-type value was given."""
37
+
38
+ def __init__(self, *, role: str, got: object) -> None:
39
+ super().__init__(
40
+ f"Expected a class for {role}, got {type(got).__name__} instance"
41
+ )
@@ -0,0 +1,23 @@
1
+ from datetime import datetime, timezone
2
+ from typing import List, Protocol, runtime_checkable
3
+
4
+ from .base_inmutable import BaseInmutable
5
+ from .fields.fields import Field
6
+
7
+
8
+ class Event(BaseInmutable):
9
+ emmited_at: datetime = Field(
10
+ default_factory=lambda: datetime.now(timezone.utc), init=False
11
+ )
12
+
13
+
14
+ @runtime_checkable
15
+ class EventEmitter(Protocol):
16
+ def _emit(self, event: Event) -> None:
17
+ pass
18
+
19
+ def _clear_events(self) -> None:
20
+ pass
21
+
22
+ def poll_events(self) -> List[Event]:
23
+ pass
@@ -0,0 +1,3 @@
1
+ from .fields import Field, PrivateField
2
+
3
+ __all__ = ["Field", "PrivateField"]
@@ -0,0 +1,94 @@
1
+ import re
2
+ from typing import Any, Callable, overload
3
+
4
+ import annotated_types
5
+ from pydantic import Field as PField
6
+ from pydantic import PrivateAttr
7
+
8
+
9
+ class Unset:
10
+ def __repr__(self) -> str:
11
+ return "UNSET FIELD"
12
+
13
+
14
+ @overload
15
+ def Field(
16
+ default: Any,
17
+ *,
18
+ default_factory: Callable[[], Any] | None = ...,
19
+ gt: annotated_types.SupportsGt | None = ...,
20
+ ge: annotated_types.SupportsGe | None = ...,
21
+ lt: annotated_types.SupportsLt | None = ...,
22
+ le: annotated_types.SupportsLe | None = ...,
23
+ multiple_of: float | None = ...,
24
+ strict: bool | None = ...,
25
+ min_length: int | None = ...,
26
+ max_length: int | None = ...,
27
+ pattern: str | re.Pattern[str] | None = ...,
28
+ allow_inf_nan: bool | None = ...,
29
+ max_digits: int | None = ...,
30
+ decimal_places: int | None = ...,
31
+ init: bool = True,
32
+ ) -> Any: ...
33
+
34
+
35
+ @overload
36
+ def Field(
37
+ *,
38
+ default_factory: Callable[[], Any],
39
+ gt: annotated_types.SupportsGt | None = ...,
40
+ ge: annotated_types.SupportsGe | None = ...,
41
+ lt: annotated_types.SupportsLt | None = ...,
42
+ le: annotated_types.SupportsLe | None = ...,
43
+ multiple_of: float | None = ...,
44
+ strict: bool | None = ...,
45
+ min_length: int | None = ...,
46
+ max_length: int | None = ...,
47
+ pattern: str | re.Pattern[str] | None = ...,
48
+ allow_inf_nan: bool | None = ...,
49
+ max_digits: int | None = ...,
50
+ decimal_places: int | None = ...,
51
+ init: bool = True,
52
+ ) -> Any: ...
53
+
54
+
55
+ @overload
56
+ def Field(
57
+ *,
58
+ gt: annotated_types.SupportsGt | None = ...,
59
+ ge: annotated_types.SupportsGe | None = ...,
60
+ lt: annotated_types.SupportsLt | None = ...,
61
+ le: annotated_types.SupportsLe | None = ...,
62
+ multiple_of: float | None = ...,
63
+ strict: bool | None = ...,
64
+ min_length: int | None = ...,
65
+ max_length: int | None = ...,
66
+ pattern: str | re.Pattern[str] | None = ...,
67
+ allow_inf_nan: bool | None = ...,
68
+ max_digits: int | None = ...,
69
+ decimal_places: int | None = ...,
70
+ init: bool = True,
71
+ ) -> Any: ...
72
+
73
+
74
+ def Field(default: Any = ..., **kwargs: Any) -> Any:
75
+ return PField(default, **kwargs)
76
+
77
+
78
+ @overload
79
+ def PrivateField(
80
+ default: Any = ..., *, default_factory: None = None
81
+ ) -> Any: ...
82
+
83
+
84
+ @overload
85
+ def PrivateField(*, default_factory: Callable[[], Any]) -> Any: ...
86
+
87
+
88
+ def PrivateField(
89
+ default: Any = ..., *, default_factory: Callable[[], Any] | None = None
90
+ ) -> Any:
91
+ if default_factory is not None:
92
+ return PrivateAttr(default_factory=default_factory, init=False)
93
+ field_default = Unset() if default is ... else default
94
+ return PrivateAttr(default=field_default, init=False)
@@ -0,0 +1,75 @@
1
+ from typing import Annotated, Any, Type, get_args, get_origin
2
+
3
+ from pydantic import BaseModel, ConfigDict
4
+ from pydantic.fields import ModelPrivateAttr
5
+
6
+ from .validators import is_validator
7
+
8
+ VALIDATION_MODEL_KEY = "__validation_model__"
9
+ RAW_MODEL_KEY = "__raw_model__"
10
+
11
+
12
+ def get_parent_models(
13
+ bases: tuple[Type[Any], ...], key: str
14
+ ) -> tuple[Type[Any], ...]:
15
+ parent_models = tuple(getattr(b, key) for b in bases if hasattr(b, key))
16
+ if not parent_models:
17
+ parent_models = (BaseModel,)
18
+ return parent_models
19
+
20
+
21
+ def get_model_config(cls: Type[Any]) -> ConfigDict:
22
+ existing_config = getattr(cls, "model_config", None)
23
+ if isinstance(existing_config, dict):
24
+ return ConfigDict(**existing_config, arbitrary_types_allowed=True)
25
+ return ConfigDict(arbitrary_types_allowed=True)
26
+
27
+
28
+ def make_validation_model(
29
+ cls: Type[Any],
30
+ name: str,
31
+ bases: tuple[Type[Any], ...],
32
+ ) -> Type[BaseModel]:
33
+ full_ns = {
34
+ "model_config": get_model_config(cls),
35
+ "__module__": cls.__module__,
36
+ "__qualname__": f"{cls.__qualname__}.{name}ValidationModel",
37
+ "__annotations__": cls.__annotations__,
38
+ **{k: getattr(cls, k) for k in cls.__annotations__ if hasattr(cls, k)},
39
+ }
40
+ for k, v in cls.__dict__.copy().items():
41
+ if validator_info := is_validator(v):
42
+ full_ns[k] = validator_info(v)
43
+
44
+ parent_models = get_parent_models(bases, VALIDATION_MODEL_KEY)
45
+ return type(name + "ValidationModel", parent_models, full_ns)
46
+
47
+
48
+ def strip_validators(annotation):
49
+ if get_origin(annotation) is Annotated:
50
+ return get_args(annotation)[0]
51
+ return annotation
52
+
53
+
54
+ def make_raw_model(
55
+ cls: Type[Any],
56
+ name: str,
57
+ bases: tuple[Type[Any], ...],
58
+ ) -> Type[BaseModel]:
59
+ annotations = {
60
+ k: strip_validators(v) for k, v in cls.__annotations__.items()
61
+ }
62
+ ns: dict[str, Any] = {
63
+ "model_config": get_model_config(cls),
64
+ "__module__": cls.__module__,
65
+ "__qualname__": f"{cls.__qualname__}.{name}RawModel",
66
+ "__annotations__": annotations,
67
+ }
68
+
69
+ for base in reversed(cls.__mro__):
70
+ for k, v in getattr(base, "__dict__", {}).items():
71
+ if isinstance(v, ModelPrivateAttr):
72
+ ns[k] = v
73
+
74
+ parent_models = get_parent_models(bases, RAW_MODEL_KEY)
75
+ return type(name + "RawModel", parent_models, ns)
@@ -0,0 +1,15 @@
1
+ from pydantic import AfterValidator, BeforeValidator
2
+
3
+ from .validators import (
4
+ field_validator,
5
+ is_validator,
6
+ post_init,
7
+ )
8
+
9
+ __all__ = [
10
+ "AfterValidator",
11
+ "BeforeValidator",
12
+ "field_validator",
13
+ "is_validator",
14
+ "post_init",
15
+ ]
@@ -0,0 +1,59 @@
1
+ from typing import Callable, Literal
2
+
3
+ from pydantic import (
4
+ field_validator as pydantic_field_validator,
5
+ )
6
+ from pydantic import (
7
+ model_validator as pydantic_model_validator,
8
+ )
9
+
10
+ VALIDATOR_KEY = "__field_validator_info__"
11
+
12
+
13
+ class ValidatorInfo:
14
+ def __init__(self, *args, validation: Callable, **kwargs):
15
+ self.args = args
16
+ self.kwargs = kwargs
17
+ self.validation = validation
18
+
19
+ def __call__(self, fn):
20
+ return self.validation(*self.args, **self.kwargs)(fn)
21
+
22
+
23
+ def field_validator(
24
+ *fields,
25
+ mode: Literal["before", "after"] = "before",
26
+ check_fields: bool = False,
27
+ ):
28
+ def decorator(fn):
29
+ if not isinstance(fn, classmethod):
30
+ fn = classmethod(fn)
31
+ setattr(
32
+ fn,
33
+ VALIDATOR_KEY,
34
+ ValidatorInfo(
35
+ validation=pydantic_field_validator,
36
+ *fields,
37
+ mode=mode,
38
+ check_fields=check_fields,
39
+ ),
40
+ )
41
+ return fn
42
+
43
+ return decorator
44
+
45
+
46
+ def post_init(fn):
47
+ setattr(
48
+ fn,
49
+ VALIDATOR_KEY,
50
+ ValidatorInfo(validation=pydantic_model_validator, mode="after"),
51
+ )
52
+ return fn
53
+
54
+
55
+ def is_validator(fn) -> ValidatorInfo | None:
56
+ has_key = getattr(fn, VALIDATOR_KEY, None)
57
+ if not has_key and isinstance(fn, classmethod):
58
+ has_key = getattr(fn.__func__, VALIDATOR_KEY, None)
59
+ return has_key
@@ -0,0 +1,6 @@
1
+ from .bounded_context import BoundedContext
2
+ from .entity import Entity, RootEntity
3
+ from .service import Service
4
+ from .value_object import ValueObject
5
+
6
+ __all__ = ["BoundedContext", "Entity", "RootEntity", "Service", "ValueObject"]
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, Optional, TypeAlias
4
+
5
+ from aod._internal.core.domain_exception import (
6
+ ClassExpectedError,
7
+ InvalidEntityTypeError,
8
+ InvalidRootEntityTypeError,
9
+ InvalidServiceTypeError,
10
+ )
11
+
12
+ from .entity import Entity, RootEntity
13
+ from .service import Service
14
+
15
+ RootEntityType: TypeAlias = type[RootEntity]
16
+ ServiceType: TypeAlias = type[Service]
17
+
18
+
19
+ class BoundedContext:
20
+ """
21
+ A bounded context defined by its aggregate roots.
22
+
23
+ This class expects a collection of *entity classes*, not instances.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ aggregate_roots: Optional[Iterable[RootEntityType]] = None,
29
+ services: Optional[Iterable[ServiceType]] = None,
30
+ ):
31
+ if aggregate_roots is None:
32
+ aggregate_roots = []
33
+ if services is None:
34
+ services = []
35
+
36
+ for item in aggregate_roots:
37
+ if not isinstance(item, type):
38
+ raise ClassExpectedError(role="aggregate root", got=item)
39
+ if not issubclass(item, Entity):
40
+ raise InvalidEntityTypeError(item.__name__)
41
+ if not item.is_root():
42
+ raise InvalidRootEntityTypeError(item.__name__)
43
+
44
+ for service in services:
45
+ if not isinstance(service, type):
46
+ raise ClassExpectedError(role="service", got=service)
47
+ if not issubclass(service, Service):
48
+ raise InvalidServiceTypeError(service.__name__)
49
+
50
+ self.aggregate_roots: tuple[RootEntityType, ...] = tuple(
51
+ aggregate_roots
52
+ )
53
+ self.services: tuple[ServiceType, ...] = tuple(services)
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import ClassVar, Generator, List
4
+
5
+ from aod._internal.core.base_mutable import BaseMutable, MutableBaseMeta
6
+ from aod._internal.core.event_emitter import Event, EventEmitter
7
+ from aod._internal.core.fields import PrivateField
8
+
9
+
10
+ class EntityMeta(MutableBaseMeta):
11
+ def __new__(mcls, name, bases, namespace, root=None):
12
+ cls = super().__new__(mcls, name, bases, namespace)
13
+ if root is not None:
14
+ cls.__aggregate_root__ = bool(root)
15
+ return cls
16
+
17
+
18
+ class Entity(BaseMutable, metaclass=EntityMeta):
19
+ __aggregate_root__: ClassVar[bool] = False
20
+ _events: List[Event] = PrivateField(default_factory=list)
21
+
22
+ @classmethod
23
+ def is_root(cls) -> bool:
24
+ return cls.__aggregate_root__
25
+
26
+ def _emit(self, event: Event) -> None:
27
+ self._events.append(event)
28
+
29
+ def poll_events(self) -> List[Event]:
30
+ events: list[Event] = list(self._events)
31
+
32
+ for emitter in self._self_emitters():
33
+ events.extend(emitter.poll_events())
34
+
35
+ events.sort(key=lambda e: e.emmited_at)
36
+ return events
37
+
38
+ def _clear_events(self) -> None:
39
+ self._events.clear()
40
+
41
+ for emitter in self._self_emitters():
42
+ emitter._clear_events()
43
+
44
+ def _self_emitters(self) -> Generator[EventEmitter, None, None]:
45
+ for emitter in vars(self).values():
46
+ if isinstance(emitter, EventEmitter):
47
+ yield emitter
48
+
49
+
50
+ class RootEntity(Entity, root=True):
51
+ pass
@@ -0,0 +1,3 @@
1
+ class Service:
2
+ """Domain service base class (stateless operations / coordination)."""
3
+
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import List
4
+
5
+ from aod._internal.core.base_inmutable import BaseInmutable
6
+ from aod._internal.core.event_emitter import Event
7
+ from aod._internal.core.fields import PrivateField
8
+
9
+
10
+ class ValueObject(BaseInmutable):
11
+ """Domain Value Object base (immutable) with domain events."""
12
+
13
+ _events: List[Event] = PrivateField(default_factory=list)
14
+
15
+ def _emit(self, event: Event) -> None:
16
+ self._events.append(event)
17
+
18
+ def _clear_events(self) -> None:
19
+ self._events.clear()
20
+
21
+ def poll_events(self) -> List[Event]:
22
+ return list(self._events)
File without changes
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: attack-on-domain
3
+ Version: 0.0.1
4
+ Summary: DDD building blocks: entities, value objects, bounded contexts, and validation helpers.
5
+ Author: Alfonso Cuesta
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/AlfonsoCuesta/attack-on-domain
8
+ Project-URL: Repository, https://github.com/AlfonsoCuesta/attack-on-domain
9
+ Project-URL: Issues, https://github.com/AlfonsoCuesta/attack-on-domain/issues
10
+ Keywords: ddd,domain-driven-design,entity,value-object
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.14
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: pydantic>=2.12.4
22
+ Requires-Dist: typing-inspect>=0.9.0
23
+ Dynamic: license-file
24
+
25
+ # attack-on-domain
26
+
27
+ Helpers for **domain-driven design** in Python: entities, value objects, bounded contexts, domain events, and Pydantic v2–based validation.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install attack-on-domain
33
+ ```
34
+
35
+ With **uv** in another project:
36
+
37
+ ```bash
38
+ uv add attack-on-domain
39
+ ```
40
+
41
+ Or install into the active environment:
42
+
43
+ ```bash
44
+ uv pip install attack-on-domain
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ Import only from the top-level package:
50
+
51
+ ```python
52
+ from aod import (
53
+ BoundedContext,
54
+ DomainEvent,
55
+ DomainException,
56
+ Entity,
57
+ ValueObject,
58
+ )
59
+ ```
60
+
61
+ Requires **Python 3.14+**.
@@ -0,0 +1,28 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ code/aod/__init__.py
5
+ code/aod/py.typed
6
+ code/aod/_internal/__init__.py
7
+ code/aod/_internal/core/__init__.py
8
+ code/aod/_internal/core/__main__.py
9
+ code/aod/_internal/core/base_inmutable.py
10
+ code/aod/_internal/core/base_mutable.py
11
+ code/aod/_internal/core/base_validator.py
12
+ code/aod/_internal/core/domain_exception.py
13
+ code/aod/_internal/core/event_emitter.py
14
+ code/aod/_internal/core/model_maker.py
15
+ code/aod/_internal/core/fields/__init__.py
16
+ code/aod/_internal/core/fields/fields.py
17
+ code/aod/_internal/core/validators/__init__.py
18
+ code/aod/_internal/core/validators/validators.py
19
+ code/aod/_internal/domain/__init__.py
20
+ code/aod/_internal/domain/bounded_context.py
21
+ code/aod/_internal/domain/entity.py
22
+ code/aod/_internal/domain/service.py
23
+ code/aod/_internal/domain/value_object.py
24
+ code/attack_on_domain.egg-info/PKG-INFO
25
+ code/attack_on_domain.egg-info/SOURCES.txt
26
+ code/attack_on_domain.egg-info/dependency_links.txt
27
+ code/attack_on_domain.egg-info/requires.txt
28
+ code/attack_on_domain.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ pydantic>=2.12.4
2
+ typing-inspect>=0.9.0
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "attack-on-domain"
7
+ version = "0.0.1"
8
+ description = "DDD building blocks: entities, value objects, bounded contexts, and validation helpers."
9
+ readme = "README.md"
10
+ requires-python = ">=3.14"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "Alfonso Cuesta" },
15
+ ]
16
+ keywords = ["ddd", "domain-driven-design", "entity", "value-object"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Software Development :: Libraries :: Python Modules",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = [
27
+ "pydantic>=2.12.4",
28
+ "typing-inspect>=0.9.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/AlfonsoCuesta/attack-on-domain"
33
+ Repository = "https://github.com/AlfonsoCuesta/attack-on-domain"
34
+ Issues = "https://github.com/AlfonsoCuesta/attack-on-domain/issues"
35
+
36
+ [tool.setuptools.package-data]
37
+ aod = ["py.typed"]
38
+
39
+ [tool.setuptools.package-dir]
40
+ "" = "code"
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["code"]
44
+ include = ["aod*"]
45
+ exclude = ["tests*", "tests"]
46
+
47
+ [dependency-groups]
48
+ dev = [
49
+ "black>=25.11.0",
50
+ "mypy>=1.20.2",
51
+ "pre-commit>=4.4.0",
52
+ "pytest>=9.0.2",
53
+ "twine>=6.0.0",
54
+ ]
55
+
56
+ [tool.pytest.ini_options]
57
+ pythonpath = ["code"]
58
+ testpaths = ["code/tests"]
59
+
60
+ [tool.mypy]
61
+ python_version = "3.14"
62
+ mypy_path = ["code"]
63
+ files = ["code"]
64
+ explicit_package_bases = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+