orionis 0.321.0__py3-none-any.whl → 0.323.0__py3-none-any.whl

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.
@@ -1,292 +0,0 @@
1
- import re
2
- import inspect
3
- from abc import ABC
4
- from typing import Any, Callable, Set, Type
5
- from orionis._container.exception import OrionisContainerValueError, OrionisContainerTypeError
6
- from orionis._contracts.container.container_integrity import IContainerIntegrity
7
-
8
- class ContainerIntegrity(IContainerIntegrity):
9
-
10
- @staticmethod
11
- def ensureImplementation(abstract: Type, concrete: Type, raise_exception: bool = True) -> bool:
12
- """
13
- Strictly verify that 'concrete' implements all abstract methods of 'abstract'.
14
-
15
- Args:
16
- abstract: Abstract class or interface to verify against
17
- concrete: Concrete class that should implement the abstract class
18
-
19
- Raises:
20
- OrionisContainerTypeError: If concrete doesn't properly implement abstract
21
- """
22
-
23
- # Check if abstract is a class
24
- if not inspect.isclass(abstract):
25
- if raise_exception:
26
- raise OrionisContainerTypeError(
27
- f"Abstract must be a class, got {type(abstract).__name__}"
28
- )
29
- return False
30
-
31
- # Check if concrete is a class
32
- if not inspect.isclass(concrete):
33
- if raise_exception:
34
- raise OrionisContainerTypeError(
35
- f"Concrete must be a class, got {type(concrete).__name__}"
36
- )
37
- return False
38
-
39
- # Check if concrete inherits from abstract
40
- if not issubclass(concrete, abstract):
41
- if raise_exception:
42
- raise OrionisContainerTypeError(
43
- f"{concrete.__name__} must inherit from {abstract.__name__}"
44
- )
45
- return False
46
-
47
- abstract_methods: Set[str] = set()
48
- for base in abstract.__mro__:
49
- if hasattr(base, '__abstractmethods__'):
50
- abstract_methods.update(base.__abstractmethods__)
51
-
52
- if not abstract_methods:
53
- return # No abstract methods to implement
54
-
55
- class_methods = {
56
- name for name, member in inspect.getmembers(concrete)
57
- if not name.startswith("_") and inspect.isfunction(member)
58
- }
59
-
60
- missing_methods = abstract_methods - class_methods
61
- if missing_methods:
62
- raise OrionisContainerTypeError(
63
- f"{concrete.__name__} must implement: {sorted(missing_methods)}"
64
- )
65
-
66
- def ensureImplementation(abstract: Type, concrete: Type) -> None:
67
- """
68
- Verify at runtime if `concrete` implements all methods of `abstract`.
69
-
70
- :param abstract: Abstract class or interface.
71
- :param concrete: Concrete class that should implement the abstract class.
72
- :raises TypeError: If `concrete` does not implement all methods of `abstract`.
73
- """
74
- # Get public methods of the interface (excluding magic methods)
75
- interface_methods = {
76
- name for name, func in inspect.getmembers(abstract, predicate=inspect.isfunction)
77
- if not name.startswith("_")
78
- }
79
-
80
- # Get public methods of the concrete class
81
- class_methods = {
82
- name for name, func in inspect.getmembers(concrete, predicate=inspect.isfunction)
83
- if not name.startswith("_")
84
- }
85
-
86
- # Verify that all interface methods are in the concrete class
87
- if not interface_methods.issubset(class_methods):
88
- missing_methods = interface_methods - class_methods
89
- raise OrionisContainerTypeError(f"{concrete.__name__} does not implement the required methods of {abstract.__name__}: {missing_methods}")
90
-
91
-
92
- @staticmethod
93
- def ensureIsAbstract(abstract: Callable[..., Any]) -> None:
94
- """
95
- Ensure that the given abstract is a valid abstract class.
96
-
97
- :param abstract: Class to check
98
- :raises OrionisContainerValueError: If the class is not a valid abstract interface
99
- """
100
- if not isinstance(abstract, type) or not issubclass(abstract, ABC) or abstract is ABC:
101
- raise OrionisContainerValueError("The provided class must inherit from ABC and not be ABC itself.")
102
-
103
- if not any(getattr(attr, "__isabstractmethod__", False) for attr in abstract.__dict__.values()):
104
- raise OrionisContainerValueError("The provided class must define at least one abstract method.")
105
-
106
- @staticmethod
107
- def ensureIsCallable(concrete: Callable[..., Any]) -> None:
108
- """
109
- Ensure that the given implementation is callable or instantiable.
110
-
111
- Parameters
112
- ----------
113
- concrete : Callable[..., Any]
114
- The implementation to check.
115
-
116
- Raises
117
- ------
118
- OrionisContainerTypeError
119
- If the implementation is not callable.
120
- """
121
- if not callable(concrete):
122
- raise OrionisContainerTypeError(f"The implementation '{str(concrete)}' must be callable or an instantiable class.")
123
-
124
- @staticmethod
125
- def ensureIsInstance(instance: Any) -> None:
126
- """
127
- Ensure that the given instance is a valid object.
128
-
129
- Parameters
130
- ----------
131
- instance : Any
132
- The instance to check.
133
-
134
- Raises
135
- ------
136
- OrionisContainerValueError
137
- If the instance is not a valid object.
138
- """
139
- if not isinstance(instance, object):
140
- raise OrionisContainerValueError(f"The instance '{str(instance)}' must be a valid object.")
141
-
142
- module = type(instance).__module__
143
- if module in ['builtins', 'abc']:
144
- raise OrionisContainerValueError(f"The instance '{str(instance)}' is not a valid user-defined object. It belongs to the '{module}' module.")
145
-
146
- @staticmethod
147
- def ensureNotMain(concrete: Callable[..., Any]) -> str:
148
- """
149
- Ensure that a class is not defined in the main script.
150
-
151
- Parameters
152
- ----------
153
- concrete : Callable[..., Any]
154
- The class or function to check.
155
-
156
- Returns
157
- -------
158
- str
159
- The fully qualified name of the class.
160
-
161
- Raises
162
- ------
163
- OrionisContainerValueError
164
- If the class is defined in the main module.
165
- """
166
- if concrete.__module__ == "__main__":
167
- raise OrionisContainerValueError("Cannot register a class from the (__main__) module in the container.")
168
-
169
- @staticmethod
170
- def ensureIsAlias(name: str) -> bool:
171
- """
172
- Ensure that the given alias name is a valid string, with no special characters or spaces,
173
- and it is not a primitive type.
174
-
175
- Parameters
176
- ----------
177
- name : str
178
- The alias name to check.
179
-
180
- Raises
181
- ------
182
- OrionisContainerValueError
183
- If the alias is invalid.
184
- """
185
- if not isinstance(name, str):
186
- raise OrionisContainerValueError(f"The alias '{name}' must be a string.")
187
-
188
- if not re.match(r'^[a-zA-Z0-9_:]+$', name):
189
- raise OrionisContainerValueError(
190
- f"The alias '{name}' can only contain letters, numbers, underscores, and colons, without spaces or other special characters."
191
- )
192
-
193
- if name in {
194
- int, "int",
195
- float, "float",
196
- str, "str",
197
- bool, "bool",
198
- bytes, "bytes",
199
- type(None), "None",
200
- complex, "complex",
201
- list, "list",
202
- tuple, "tuple",
203
- dict, "dict",
204
- set, "set",
205
- frozenset, "frozenset"
206
- }:
207
- raise OrionisContainerValueError(f"The alias '{name}' cannot be a primitive type.")
208
-
209
- @staticmethod
210
- def isAlias(name: str) -> bool:
211
- """
212
- Check if the given alias name is a valid string, with no special characters or spaces,
213
- and it is not a primitive type.
214
-
215
- Parameters
216
- ----------
217
- name : str
218
- The alias name to check.
219
-
220
- Returns
221
- -------
222
- bool
223
- True if the alias is valid, False otherwise.
224
- """
225
- try:
226
- ContainerIntegrity.ensureIsAlias(name)
227
- return True
228
- except OrionisContainerValueError:
229
- return False
230
-
231
- @staticmethod
232
- def isCallable(concrete: Callable[..., Any]) -> bool:
233
- """
234
- Check if the given implementation is callable or instantiable.
235
-
236
- Parameters
237
- ----------
238
- concrete : Callable[..., Any]
239
- The implementation to check.
240
-
241
- Returns
242
- -------
243
- bool
244
- True if the implementation is callable, False otherwise.
245
- """
246
- try:
247
- ContainerIntegrity.ensureIsCallable(concrete)
248
- return True
249
- except OrionisContainerTypeError:
250
- return False
251
-
252
- @staticmethod
253
- def isInstance(instance: Any) -> bool:
254
- """
255
- Check if the given instance is a valid object.
256
-
257
- Parameters
258
- ----------
259
- instance : Any
260
- The instance to check.
261
-
262
- Returns
263
- -------
264
- bool
265
- True if the instance is valid, False otherwise.
266
- """
267
- try:
268
- ContainerIntegrity.ensureIsInstance(instance)
269
- return True
270
- except OrionisContainerValueError:
271
- return False
272
-
273
- @staticmethod
274
- def isAbstract(abstract: Callable[..., Any]) -> bool:
275
- """
276
- Check if the given abstract is a valid abstract class.
277
-
278
- Parameters
279
- ----------
280
- abstract : Callable[..., Any]
281
- The class to check.
282
-
283
- Returns
284
- -------
285
- bool
286
- True if the class is a valid abstract interface, False otherwise.
287
- """
288
- try:
289
- ContainerIntegrity.ensureIsAbstract(abstract)
290
- return True
291
- except OrionisContainerValueError:
292
- return False
@@ -1,54 +0,0 @@
1
- class OrionisContainerException(Exception):
2
- """
3
- Excepción personalizada para errores relacionados con el contenedor de inyección de dependencias Orionis.
4
- """
5
-
6
- def __init__(self, message: str) -> None:
7
- """
8
- Inicializa la excepción con un mensaje de error.
9
-
10
- Args:
11
- message (str): Mensaje descriptivo del error.
12
- """
13
- super().__init__(message)
14
-
15
- def __str__(self) -> str:
16
- """Retorna una representación en cadena de la excepción."""
17
- return f"[OrionisContainerException] {self.args[0]}"
18
-
19
-
20
- class OrionisContainerValueError(ValueError):
21
- """
22
- Excepción personalizada para errores de tipo ValueError en el contenedor Orionis.
23
- """
24
-
25
- def __init__(self, message: str) -> None:
26
- """
27
- Inicializa la excepción con un mensaje de error.
28
-
29
- Args:
30
- message (str): Mensaje descriptivo del error.
31
- """
32
- super().__init__(message)
33
-
34
- def __str__(self) -> str:
35
- """Retorna una representación en cadena de la excepción."""
36
- return f"[OrionisContainerValueError] {self.args[0]}"
37
-
38
- class OrionisContainerTypeError(TypeError):
39
- """
40
- Custom exception for TypeError related to the Orionis container.
41
- """
42
-
43
- def __init__(self, message: str) -> None:
44
- """
45
- Initializes the exception with an error message.
46
-
47
- Args:
48
- message (str): Descriptive error message.
49
- """
50
- super().__init__(message)
51
-
52
- def __str__(self) -> str:
53
- """Returns a string representation of the exception."""
54
- return f"[OrionisContainerTypeError] {self.args[0]}"
@@ -1,13 +0,0 @@
1
- from enum import Enum
2
-
3
- class Lifetime(Enum):
4
- """Defines the lifecycle types for dependency injection."""
5
-
6
- # Creates a new instance every time it is requested
7
- TRANSIENT = "transient"
8
-
9
- # A single instance is shared throughout the application
10
- SINGLETON = "singleton"
11
-
12
- # A new instance is created per request or context
13
- SCOPED = "scoped"
@@ -1,64 +0,0 @@
1
- from typing import Any, Callable
2
- from orionis._container.container import Container
3
- from orionis._container.exception import OrionisContainerValueError
4
-
5
- class Resolve:
6
- """
7
- A class to resolve dependencies from the dependency injection container.
8
-
9
- This class ensures that a given abstract class or alias exists in the container
10
- and resolves the associated service when an instance is created.
11
-
12
- Parameters
13
- ----------
14
- abstract_or_alias : Callable[..., Any] or str
15
- The abstract class, alias, or callable to resolve from the container.
16
-
17
- Returns
18
- -------
19
- Any
20
- The service associated with the abstract class or alias.
21
-
22
- Raises
23
- ------
24
- OrionisContainerValueError
25
- If the abstract class or alias is not found in the container.
26
-
27
- Examples
28
- --------
29
- >>> container = Container()
30
- >>> container.bind("my_service", MyService)
31
- >>> container.alias("my_alias", "my_service")
32
- >>> service = Resolve("my_alias") # Returns the service associated with "my_alias"
33
- >>> service = Resolve(MyService) # Returns the service associated with MyService
34
- """
35
-
36
- def __new__(cls, abstract_or_alias: Callable[..., Any] | str):
37
- """
38
- Create an instance of Resolve and return the resolved service.
39
-
40
- Parameters
41
- ----------
42
- abstract_or_alias : Callable[..., Any] or str
43
- The abstract class, alias, or callable to resolve from the container.
44
-
45
- Returns
46
- -------
47
- Any
48
- The service associated with the abstract class or alias.
49
-
50
- Raises
51
- ------
52
- OrionisContainerValueError
53
- If the abstract class or alias is not found in the container.
54
- """
55
-
56
- # Validate that the abstract or alias exists in the container
57
- container = Container()
58
- if not container.bound(abstract_or_alias):
59
- raise OrionisContainerValueError(
60
- f"Service or alias '{abstract_or_alias}' not found in the container."
61
- )
62
-
63
- # Resolve and return the service associated with the abstract or alias
64
- # return AsyncExecutor.run(container.make(abstract_or_alias))
File without changes