ddutils 0.3.3__tar.gz → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ddutils
3
- Version: 0.3.3
3
+ Version: 0.4.0
4
4
  Summary: Domain Driven Utils Library
5
5
  Keywords: python,ddutils
6
6
  Author: davyddd
@@ -34,9 +34,14 @@ Install the library using pip:
34
34
  pip install ddutils
35
35
  ```
36
36
 
37
+ ## Compatibility
38
+
39
+ Python 3.11 to 3.14, no runtime dependencies. What changed in each release, breaking changes included, is in the
40
+ [GitHub releases](https://github.com/davyddd/ddutils/releases).
41
+
37
42
  ## Development
38
43
 
39
- The project runs entirely in Docker. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:
44
+ The project runs entirely in Docker. The tests need no external services. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:
40
45
 
41
46
  ```bash
42
47
  fab build # build the dev image
@@ -54,6 +59,10 @@ run `uvx copier update` to pull in template updates.
54
59
  Utilities for inspecting and working with Python type hints and generic types.
55
60
  These helpers let you analyze and modify complex annotations at runtime.
56
61
 
62
+ They work on classes and parametrized generics (`list[int]`, `Dict[str, int]`, a `NewType`). A union, `Optional`
63
+ included, a `Literal`, a `TypeVar`, `Any` or a string annotation is not a type and raises `TypeError` rather than
64
+ returning `False`; strip the `Optional` with [get_annotation_without_optional](#get_annotation_without_optional) first.
65
+
57
66
  ### get_annotation_origin
58
67
 
59
68
  Returns the base (origin) type of a generic annotation, unwrapping `NewType` and handling generic aliases recursively.
@@ -107,7 +116,7 @@ is_complex_sequence(dict) # False
107
116
  ### get_complex_sequence_element_annotation
108
117
 
109
118
  Returns the element type from a sequence annotation.
110
- Raises `ValueError` if the annotation doesn’t specify an element type.
119
+ Raises `ValueError` if the annotation is not a complex sequence or doesn’t specify an element type.
111
120
 
112
121
  ```python
113
122
  from typing import List, Set
@@ -120,7 +129,8 @@ get_complex_sequence_element_annotation(Set[str]) # <class 'str'>
120
129
 
121
130
  ### get_dict_items_annotation
122
131
 
123
- Returns the key and value types from a dictionary annotation.
132
+ Returns the key and value types from a dictionary annotation. Raises `TypeError` for an annotation that is not a
133
+ `dict`, `ValueError` for a bare `dict` without arguments.
124
134
 
125
135
  ```python
126
136
  from typing import Dict
@@ -167,7 +177,8 @@ Helper functions for inspecting and extending class-level behavior
167
177
  ### classproperty
168
178
 
169
179
  Works like `@property`, but for class attributes.
170
- Can be accessed as `ClassName.property_name` without creating an instance.
180
+ Can be accessed as `ClassName.property_name` without creating an instance. Read-only in the sense that there is
181
+ no setter: assigning to the attribute replaces the descriptor on the class.
171
182
 
172
183
  ```python
173
184
  from ddutils.class_helpers import classproperty
@@ -216,7 +227,8 @@ get_origin_class_of_method(B, 'method') # <class 'A'>
216
227
  ### get_generic_base_argument
217
228
 
218
229
  Returns the type argument a class bound to a generic base when subclassing it. `None` when the base was not
219
- subscripted, the `TypeVar` itself when the subclass is still generic.
230
+ subscripted, the `TypeVar` itself when the subclass is still generic. `position` picks the argument of a base
231
+ with several type parameters (default `0`).
220
232
 
221
233
  ```python
222
234
  from typing import Generic, TypeVar
@@ -240,9 +252,11 @@ get_generic_base_argument(Repository, Repository) # None
240
252
 
241
253
  ### require_class_attribute
242
254
 
243
- Returns a class attribute that subclasses are expected to declare, for `__init_subclass__` checks. A missing,
244
- `None` or empty value raises `AttributeError`, a value of the wrong type raises `TypeError`; both name the
245
- attribute and the class, so a misconfigured subclass fails at definition rather than on first use.
255
+ `require_class_attribute(cls, name, expected_type=None, *, allow_empty=False)` returns a class attribute that
256
+ subclasses are expected to declare, for `__init_subclass__` checks. A missing, `None` or empty value raises
257
+ `AttributeError`, a value that is not an instance of `expected_type` (a class or a tuple of classes, skipped when
258
+ `None`) raises `TypeError`; both name the attribute and the class, so a misconfigured subclass fails at definition
259
+ rather than on first use. `allow_empty=True` accepts `''`, `[]` or `{}`; numbers are never empty, `0` passes.
246
260
 
247
261
  ```python
248
262
  from typing import ClassVar
@@ -274,8 +288,10 @@ Tools for creating and modifying Python functions at runtime.
274
288
 
275
289
  ### create_new_function
276
290
 
277
- Creates a new function from an existing one, with an optional new name.
278
- Preserves default values and closures.
291
+ Creates a new function from an existing one, with an optional new name, by rebuilding its code object. It keeps
292
+ the code, globals and positional defaults (`__defaults__`); closure cells are copied as a snapshot of their
293
+ current values, so the copy does not follow later changes to the enclosed variables. Keyword-only defaults,
294
+ annotations, the docstring and `__qualname__` are not carried over.
279
295
 
280
296
  ```python
281
297
  from ddutils.function_helpers import create_new_function
@@ -373,44 +389,37 @@ Utilities for working with dates and times.
373
389
 
374
390
  ### utc_now
375
391
 
376
- Returns the current datetime in UTC timezone.
392
+ `utc_now() -> datetime`: the current time as an aware `datetime`, `datetime.now(tz=UTC)`.
377
393
 
378
394
  ## Safe Decorators
379
395
 
380
- Decorators that help functions fail safely and handle exceptions gracefully.
381
-
382
396
  ### safe_call
383
397
 
384
- Wraps a function to catch exceptions and return a default value instead of raising errors.
398
+ Retries a failing call and then falls back to a default or re-raises. The function runs up to `1 + retries`
399
+ times; an attempt fails when it raises one of `exceptions`. Without `default_result` the last error propagates,
400
+ so a `None` result always means the function returned `None`, never that an error was swallowed. Every failure
401
+ that is retried or replaced by the default is logged with its traceback unless `capture_exception=False`.
402
+ Coroutine functions are awaited inside the decorator, so the exceptions raised while awaiting are the ones handled.
385
403
 
386
404
  ```python
387
405
  import requests
406
+ from redis.exceptions import RedisError
388
407
  from ddutils.safe_decorators import safe_call
389
408
 
390
409
 
391
- @safe_call(default_result=[])
392
- def fetch_data_from_api():
393
- response = requests.get('https://api.example.com/data')
394
- return response.json()
395
-
396
-
397
- @safe_call(default_result=0, exceptions=(ValueError,))
398
- def convert_to_int(value):
399
- return int(value)
400
- ```
401
-
402
- ### retry_once_after_exception
410
+ @safe_call(default_result=0)
411
+ def count_pending() -> int:
412
+ return requests.get('https://api.example.com/pending').json()['count'] # 0 on any error
403
413
 
404
- Retries a function once if it raises an exception.
405
414
 
406
- ```python
407
- import requests
408
- from ddutils.safe_decorators import retry_once_after_exception
415
+ @safe_call(retries=1, exceptions=(requests.ConnectionError,))
416
+ def fetch_report(url: str) -> requests.Response:
417
+ return requests.get(url) # one more try on a dropped connection, then the error
409
418
 
410
419
 
411
- @retry_once_after_exception
412
- def unstable_network_call():
413
- return requests.get('https://api.example.com/unstable')
420
+ @safe_call(default_result=None, exceptions=(RedisError,), capture_exception=False)
421
+ async def get_cached_profile(profile_id: int) -> Profile | None:
422
+ return await cache.get(profile_id) # None when Redis is unavailable
414
423
  ```
415
424
 
416
425
  ## Module and Object Management
@@ -419,7 +428,8 @@ Helpers for importing and accessing modules or objects at runtime.
419
428
 
420
429
  ### get_module
421
430
 
422
- Finds a nested module by path within a parent module.
431
+ Finds a nested module by path within a parent module. Raises `ValueError` when a step of the path is not an
432
+ attribute of the module reached so far.
423
433
 
424
434
  ```python
425
435
  import os
@@ -431,7 +441,8 @@ get_module(os, ['path']) # <module 'os.path'>
431
441
 
432
442
  ### get_object_by_path
433
443
 
434
- Imports and returns an object by its full dotted path (e.g. 'json.loads').
444
+ Imports and returns an object by its full dotted path (e.g. 'json.loads'). Returns `None` instead of raising when
445
+ the path is not a string, the module cannot be imported or the attribute does not exist.
435
446
 
436
447
  ```python
437
448
  from ddutils.object_getter import get_object_by_path
@@ -446,12 +457,13 @@ A registry that keeps one object instance per scope and manages its lifetime.
446
457
 
447
458
  ### ScopedRegistry
448
459
 
449
- Keeps one object per scope. `scope_func` decides what the current scope is and returns its key; `None` means
450
- "no current scope" and makes every method raise `RuntimeError`.
460
+ `ScopedRegistry(create_func, scope_func, destructor_method_name=None)` keeps one object per scope. `scope_func`
461
+ decides what the current scope is and returns its key; `None` means "no current scope" and makes every method
462
+ raise `RuntimeError`, as does a key that is not hashable. `asyncio.current_task` as the key needs a running loop.
451
463
 
452
464
  `scope()` is the entry point into a scope: it creates the object on enter and removes it on exit, calling
453
465
  the optional destructor exactly once. Nested `scope()` blocks join the existing object and leave it alone.
454
- Concurrent first accesses with the same key call `create_func` only once.
466
+ Concurrent first accesses with the same key call `create_func` only once; `create_func` may be sync or async.
455
467
 
456
468
  ```python
457
469
  import asyncio
@@ -479,34 +491,48 @@ Lower-level methods are available when a context manager does not fit:
479
491
  - `set(**kwargs)` returns the existing object or creates it. Whoever calls it takes over the cleanup that
480
492
  `scope()` does on exit and must call `clear()` when the object is no longer needed, if it ever is: a
481
493
  per-process client may live until the process ends;
482
- - `clear()` removes the object of the current scope and calls the destructor.
494
+ - `clear()` removes the object of the current scope and calls the destructor. Without a current scope it raises
495
+ like every other method, so call it where the scope exists: anywhere for `os.getpid`, inside the task for
496
+ `asyncio.current_task`, inside the block for a token scope.
483
497
 
484
- #### Scopes kept in a ContextVar
498
+ The `kwargs` of `scope()` and `set()` go to `create_func` only when the object is created; a call that joins an
499
+ existing object ignores them. `destructor_method_name` names a sync or async method of the object; `clear()`
500
+ removes the object from the registry first and then calls it once, and an exception from it propagates.
501
+ `registry` is the plain dict behind it, keyed by scope. One `asyncio.Lock` guards creation for all keys of a
502
+ registry, so a slow `create_func` in one scope delays first accesses in the others.
485
503
 
486
- A `scope_func` that declares a `token` parameter receives a freshly generated token when `scope()` is entered
487
- and `None` on every other access. This is for a scope of one execution (an HTTP request, an actor run) rather
488
- than one task: the function stores the token in a `ContextVar`, so coroutines spawned inside the block
489
- (`gather`, `TaskGroup`, `create_task`) inherit it and share the object with the parent, while outside of
490
- `scope()` there is no key and every method raises.
504
+ #### process_loop_scope
505
+
506
+ A ready-made key for clients that are pools bound to their event loop (`redis.asyncio`, `aiokafka`,
507
+ `aerospike_native`): `(os.getpid(), asyncio.get_running_loop())`. A second loop in the same process, a script
508
+ calling `asyncio.run` twice or a test suite, gets its own client instead of an "attached to a different loop"
509
+ error, and the pid guards a forked child, whose inherited sockets must not be reused. Raises `RuntimeError`
510
+ outside of a running loop.
491
511
 
492
512
  ```python
493
- from contextvars import ContextVar
513
+ from ddutils.scoped_registry import ScopedRegistry, process_loop_scope
514
+
515
+ redis_registry = ScopedRegistry(create_func=make_redis_client, scope_func=process_loop_scope, destructor_method_name='aclose')
516
+ ```
494
517
 
495
- execution_key: ContextVar[str | None] = ContextVar('execution_key', default=None)
518
+ #### execution_scope
496
519
 
520
+ A `scope_func` that declares a `token` parameter receives a freshly generated token when `scope()` is entered
521
+ or `set()` is called, and `None` on every other access (`get`, `clear`, a nested `scope()`); a scope started by
522
+ `set()` must be ended by `clear()`. This is for a scope of one execution (an HTTP request, an actor run) rather
523
+ than one task: the function stores the token in a `ContextVar`, so coroutines spawned inside the block
524
+ (`gather`, `TaskGroup`, `create_task`) inherit it and share the object with the parent, while outside of
525
+ `scope()` there is no key and every method raises. `execution_scope(name)` is that function, with its own
526
+ `ContextVar` named `name`, so every registry gets a scope of its own:
497
527
 
498
- def execution_scope(token: str | None) -> str | None:
499
- key = execution_key.get()
500
- if key is None and token is not None: # entering scope() outside of an execution: start one
501
- execution_key.set(token)
502
- key = token
503
- return key
528
+ ```python
529
+ from ddutils.scoped_registry import ScopedRegistry, execution_scope
504
530
 
505
531
 
506
532
  async def create_log_properties(**kwargs): ...
507
533
 
508
534
 
509
- log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope)
535
+ log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope('log_properties'))
510
536
 
511
537
 
512
538
  async def middleware(headers):
@@ -536,6 +562,11 @@ per task. The connections module adds two things on top:
536
562
  Databases with transactions pass their own `connection_manager_class`: a unit of work that begins, commits
537
563
  or rolls back and closes the session on exit. It depends on the driver, so it lives in the project.
538
564
 
565
+ The factory raises `ValueError` when `default` is not among the registries and `KeyError` for an unknown alias.
566
+ `ConnectionManager` enters with `registry.set()` and no arguments, so the `create_func` of its registries takes
567
+ none (use `functools.partial`). `close()` calls `clear()` on every registry, which needs a current scope: for
568
+ `process_loop_scope` that is inside the loop the clients were opened in, for example FastAPI's lifespan.
569
+
539
570
  ```python
540
571
  import os
541
572
  from enum import Enum
@@ -575,15 +606,24 @@ await clickhouse.close()
575
606
 
576
607
  `ddutils.feature_flags` is the storage-agnostic part of feature flags: `FeatureFlagRecord` (on or off, the proportion
577
608
  of readers that see it, a free-form payload), the `FeatureFlagStorage` interface and `FeatureFlags`, which reads
578
- through a storage with a per-process cache (`BASE_TTL` plus a random jitter). While the storage fails, the last
579
- known record is served and re-read with an exponential backoff from `ERROR_TTL` up to the TTL. The storages live
580
- with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`, `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
581
-
582
- Readers see booleans and payloads, not records. `is_enabled` is the flag's switch and its proportion in one answer:
583
- off for everyone when the flag is off, on for the `proportion` of the readers when it is on, so a kill-switch is a
584
- flag with proportion 1.0. With an `idempotent_key` (a user id, an account id) the split is repeatable, the same
585
- user always lands on the same side; without one it is random per call. `get_payload` is the payload as stored; its shape is the application's,
586
- parse it there.
609
+ through a storage with a cache. The storages live with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`,
610
+ `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
611
+
612
+ `FeatureFlagRecord(enabled=False, proportion=1.0, payload={})` is what a storage holds for one flag; a flag that
613
+ does not exist reads as these defaults. The record validates itself on construction: `enabled` takes a bool or
614
+ what a storage may hold for one (`1`, `'true'`, `'yes'`, `'on'`, `'t'`, `'y'` and their negations), `proportion`
615
+ a number in 0..1, `payload` a mapping, which is copied. `from_dict` builds a record from what a storage read and
616
+ rejects unknown keys; `to_dict` is the inverse.
617
+
618
+ Readers see booleans and payloads, not records. `is_enabled(name, idempotent_key=None)` is the flag's switch and
619
+ its proportion in one answer: off for everyone when the flag is off, on for the `proportion` of the readers when
620
+ it is on. The proportion applies whenever the flag is on, so a gradual rollout is written with an explicit
621
+ `proportion` and a kill-switch keeps the default. With an `idempotent_key` (anything with a `__str__`: a user id,
622
+ an account id) the split is repeatable, the same key always lands on the same side: the bucket is
623
+ `blake2b(f'{name}:{key}')` scaled to 0..1 and compared with the proportion, so the same key may be on one side for one
624
+ flag and on the other for another. Without a key the split is random per call. `get_payload(name)` is the payload
625
+ as stored, `{}` for a missing flag; its shape is the application's, parse it there and do not mutate it, it is
626
+ the cached object.
587
627
 
588
628
  ```python
589
629
  from ddredis.feature_flags import RedisFeatureFlagStorage
@@ -591,7 +631,7 @@ from ddutils.feature_flags import FeatureFlags
591
631
 
592
632
  feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
593
633
 
594
- # a kill-switch: proportion 1.0, on or off for everyone
634
+ # a kill-switch: the default proportion, on or off for everyone
595
635
  if await feature_flags.is_enabled('new_checkout'):
596
636
  ...
597
637
 
@@ -604,11 +644,18 @@ if await feature_flags.is_enabled('email_provider_block'):
604
644
  rules = EmailProviderBlockRules.model_validate(await feature_flags.get_payload('email_provider_block'))
605
645
  ```
606
646
 
607
- A storage implements `get`, `get_map`, `put` and `delete`; `rename` defaults to
608
- put-then-delete and is overridden where the storage can do it atomically. `FeatureFlagRecord` validates itself on
609
- construction; a storage builds it with `from_dict` and, when what it read is not a valid record, logs it and reads
610
- it as the defaults. A storage failure raises `FeatureFlagStorageError`
611
- with the cause chained.
647
+ `FeatureFlags(storage, base_ttl=BASE_TTL)` caches every flag it reads for `base_ttl` (15) plus 0 to `JITTER` (5)
648
+ seconds, so the readers of a process do not re-read at once. The cache belongs to the instance: keep one per
649
+ process, and expect a `put` to take up to a TTL to be seen, also from the process that wrote it. While the
650
+ storage fails, the last known record (or the defaults) is served and logged, and the re-read is retried with a
651
+ backoff from `ERROR_TTL` (1 second) doubling on every failure up to `base_ttl`.
652
+
653
+ A storage is a `FeatureFlagStorage` with `get(name) -> FeatureFlagRecord | None`, `get_map() -> dict[str, FeatureFlagRecord]`,
654
+ `put(name, record) -> None` (create or overwrite; there is no create-only) and `delete(name) -> bool`;
655
+ `rename(old_name, new_name, record)` defaults to put-then-delete and is overridden where the storage can do it
656
+ atomically. A storage builds records with `from_dict` and, when what it read is not a valid record, logs it and
657
+ reads it as the defaults. Only a failure of the storage itself raises, as `FeatureFlagStorageError` with the cause
658
+ chained.
612
659
 
613
660
  ## Context Helpers
614
661
 
@@ -631,8 +678,16 @@ AST-based introspection for extracting exceptions from function source code.
631
678
 
632
679
  ### extract_function_exceptions
633
680
 
634
- Parses a function’s source code to find all `raise` statements and identify the exception types they use.
635
- Returns an iterator of `ExceptionInfo` objects describing each raised exception.
681
+ Parses a function’s source code to find all `raise` statements and identify the exception types they use.
682
+ Returns an iterator of `ExceptionInfo` objects describing each raised exception: `exception_class`, the
683
+ positional `args` and keyword `kwargs` of the `raise` as written, with any non-literal argument replaced by
684
+ `UNDEFINED_VALUE`. `get_kwargs()` maps them onto the parameters of the exception's `__init__`, filling in
685
+ defaults and class attributes; `get_exception_instance(dry_run=True)` builds the exception from them, with
686
+ `'<name>'` for undefined values, and returns `None` instead of raising when `dry_run`.
687
+
688
+ The function needs its source (`inspect.getsource`), so it does not work on builtins or code without a file.
689
+ A bare `raise` or `raise err` of a caught variable is skipped, an exception class that cannot be resolved by name
690
+ in the function's module or `builtins` is skipped too; `raise self.Error()` is not supported and raises `ValueError`.
636
691
 
637
692
  ## Value Helpers
638
693
 
@@ -16,9 +16,14 @@ Install the library using pip:
16
16
  pip install ddutils
17
17
  ```
18
18
 
19
+ ## Compatibility
20
+
21
+ Python 3.11 to 3.14, no runtime dependencies. What changed in each release, breaking changes included, is in the
22
+ [GitHub releases](https://github.com/davyddd/ddutils/releases).
23
+
19
24
  ## Development
20
25
 
21
- The project runs entirely in Docker. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:
26
+ The project runs entirely in Docker. The tests need no external services. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:
22
27
 
23
28
  ```bash
24
29
  fab build # build the dev image
@@ -36,6 +41,10 @@ run `uvx copier update` to pull in template updates.
36
41
  Utilities for inspecting and working with Python type hints and generic types.
37
42
  These helpers let you analyze and modify complex annotations at runtime.
38
43
 
44
+ They work on classes and parametrized generics (`list[int]`, `Dict[str, int]`, a `NewType`). A union, `Optional`
45
+ included, a `Literal`, a `TypeVar`, `Any` or a string annotation is not a type and raises `TypeError` rather than
46
+ returning `False`; strip the `Optional` with [get_annotation_without_optional](#get_annotation_without_optional) first.
47
+
39
48
  ### get_annotation_origin
40
49
 
41
50
  Returns the base (origin) type of a generic annotation, unwrapping `NewType` and handling generic aliases recursively.
@@ -89,7 +98,7 @@ is_complex_sequence(dict) # False
89
98
  ### get_complex_sequence_element_annotation
90
99
 
91
100
  Returns the element type from a sequence annotation.
92
- Raises `ValueError` if the annotation doesn’t specify an element type.
101
+ Raises `ValueError` if the annotation is not a complex sequence or doesn’t specify an element type.
93
102
 
94
103
  ```python
95
104
  from typing import List, Set
@@ -102,7 +111,8 @@ get_complex_sequence_element_annotation(Set[str]) # <class 'str'>
102
111
 
103
112
  ### get_dict_items_annotation
104
113
 
105
- Returns the key and value types from a dictionary annotation.
114
+ Returns the key and value types from a dictionary annotation. Raises `TypeError` for an annotation that is not a
115
+ `dict`, `ValueError` for a bare `dict` without arguments.
106
116
 
107
117
  ```python
108
118
  from typing import Dict
@@ -149,7 +159,8 @@ Helper functions for inspecting and extending class-level behavior
149
159
  ### classproperty
150
160
 
151
161
  Works like `@property`, but for class attributes.
152
- Can be accessed as `ClassName.property_name` without creating an instance.
162
+ Can be accessed as `ClassName.property_name` without creating an instance. Read-only in the sense that there is
163
+ no setter: assigning to the attribute replaces the descriptor on the class.
153
164
 
154
165
  ```python
155
166
  from ddutils.class_helpers import classproperty
@@ -198,7 +209,8 @@ get_origin_class_of_method(B, 'method') # <class 'A'>
198
209
  ### get_generic_base_argument
199
210
 
200
211
  Returns the type argument a class bound to a generic base when subclassing it. `None` when the base was not
201
- subscripted, the `TypeVar` itself when the subclass is still generic.
212
+ subscripted, the `TypeVar` itself when the subclass is still generic. `position` picks the argument of a base
213
+ with several type parameters (default `0`).
202
214
 
203
215
  ```python
204
216
  from typing import Generic, TypeVar
@@ -222,9 +234,11 @@ get_generic_base_argument(Repository, Repository) # None
222
234
 
223
235
  ### require_class_attribute
224
236
 
225
- Returns a class attribute that subclasses are expected to declare, for `__init_subclass__` checks. A missing,
226
- `None` or empty value raises `AttributeError`, a value of the wrong type raises `TypeError`; both name the
227
- attribute and the class, so a misconfigured subclass fails at definition rather than on first use.
237
+ `require_class_attribute(cls, name, expected_type=None, *, allow_empty=False)` returns a class attribute that
238
+ subclasses are expected to declare, for `__init_subclass__` checks. A missing, `None` or empty value raises
239
+ `AttributeError`, a value that is not an instance of `expected_type` (a class or a tuple of classes, skipped when
240
+ `None`) raises `TypeError`; both name the attribute and the class, so a misconfigured subclass fails at definition
241
+ rather than on first use. `allow_empty=True` accepts `''`, `[]` or `{}`; numbers are never empty, `0` passes.
228
242
 
229
243
  ```python
230
244
  from typing import ClassVar
@@ -256,8 +270,10 @@ Tools for creating and modifying Python functions at runtime.
256
270
 
257
271
  ### create_new_function
258
272
 
259
- Creates a new function from an existing one, with an optional new name.
260
- Preserves default values and closures.
273
+ Creates a new function from an existing one, with an optional new name, by rebuilding its code object. It keeps
274
+ the code, globals and positional defaults (`__defaults__`); closure cells are copied as a snapshot of their
275
+ current values, so the copy does not follow later changes to the enclosed variables. Keyword-only defaults,
276
+ annotations, the docstring and `__qualname__` are not carried over.
261
277
 
262
278
  ```python
263
279
  from ddutils.function_helpers import create_new_function
@@ -355,44 +371,37 @@ Utilities for working with dates and times.
355
371
 
356
372
  ### utc_now
357
373
 
358
- Returns the current datetime in UTC timezone.
374
+ `utc_now() -> datetime`: the current time as an aware `datetime`, `datetime.now(tz=UTC)`.
359
375
 
360
376
  ## Safe Decorators
361
377
 
362
- Decorators that help functions fail safely and handle exceptions gracefully.
363
-
364
378
  ### safe_call
365
379
 
366
- Wraps a function to catch exceptions and return a default value instead of raising errors.
380
+ Retries a failing call and then falls back to a default or re-raises. The function runs up to `1 + retries`
381
+ times; an attempt fails when it raises one of `exceptions`. Without `default_result` the last error propagates,
382
+ so a `None` result always means the function returned `None`, never that an error was swallowed. Every failure
383
+ that is retried or replaced by the default is logged with its traceback unless `capture_exception=False`.
384
+ Coroutine functions are awaited inside the decorator, so the exceptions raised while awaiting are the ones handled.
367
385
 
368
386
  ```python
369
387
  import requests
388
+ from redis.exceptions import RedisError
370
389
  from ddutils.safe_decorators import safe_call
371
390
 
372
391
 
373
- @safe_call(default_result=[])
374
- def fetch_data_from_api():
375
- response = requests.get('https://api.example.com/data')
376
- return response.json()
377
-
378
-
379
- @safe_call(default_result=0, exceptions=(ValueError,))
380
- def convert_to_int(value):
381
- return int(value)
382
- ```
383
-
384
- ### retry_once_after_exception
392
+ @safe_call(default_result=0)
393
+ def count_pending() -> int:
394
+ return requests.get('https://api.example.com/pending').json()['count'] # 0 on any error
385
395
 
386
- Retries a function once if it raises an exception.
387
396
 
388
- ```python
389
- import requests
390
- from ddutils.safe_decorators import retry_once_after_exception
397
+ @safe_call(retries=1, exceptions=(requests.ConnectionError,))
398
+ def fetch_report(url: str) -> requests.Response:
399
+ return requests.get(url) # one more try on a dropped connection, then the error
391
400
 
392
401
 
393
- @retry_once_after_exception
394
- def unstable_network_call():
395
- return requests.get('https://api.example.com/unstable')
402
+ @safe_call(default_result=None, exceptions=(RedisError,), capture_exception=False)
403
+ async def get_cached_profile(profile_id: int) -> Profile | None:
404
+ return await cache.get(profile_id) # None when Redis is unavailable
396
405
  ```
397
406
 
398
407
  ## Module and Object Management
@@ -401,7 +410,8 @@ Helpers for importing and accessing modules or objects at runtime.
401
410
 
402
411
  ### get_module
403
412
 
404
- Finds a nested module by path within a parent module.
413
+ Finds a nested module by path within a parent module. Raises `ValueError` when a step of the path is not an
414
+ attribute of the module reached so far.
405
415
 
406
416
  ```python
407
417
  import os
@@ -413,7 +423,8 @@ get_module(os, ['path']) # <module 'os.path'>
413
423
 
414
424
  ### get_object_by_path
415
425
 
416
- Imports and returns an object by its full dotted path (e.g. 'json.loads').
426
+ Imports and returns an object by its full dotted path (e.g. 'json.loads'). Returns `None` instead of raising when
427
+ the path is not a string, the module cannot be imported or the attribute does not exist.
417
428
 
418
429
  ```python
419
430
  from ddutils.object_getter import get_object_by_path
@@ -428,12 +439,13 @@ A registry that keeps one object instance per scope and manages its lifetime.
428
439
 
429
440
  ### ScopedRegistry
430
441
 
431
- Keeps one object per scope. `scope_func` decides what the current scope is and returns its key; `None` means
432
- "no current scope" and makes every method raise `RuntimeError`.
442
+ `ScopedRegistry(create_func, scope_func, destructor_method_name=None)` keeps one object per scope. `scope_func`
443
+ decides what the current scope is and returns its key; `None` means "no current scope" and makes every method
444
+ raise `RuntimeError`, as does a key that is not hashable. `asyncio.current_task` as the key needs a running loop.
433
445
 
434
446
  `scope()` is the entry point into a scope: it creates the object on enter and removes it on exit, calling
435
447
  the optional destructor exactly once. Nested `scope()` blocks join the existing object and leave it alone.
436
- Concurrent first accesses with the same key call `create_func` only once.
448
+ Concurrent first accesses with the same key call `create_func` only once; `create_func` may be sync or async.
437
449
 
438
450
  ```python
439
451
  import asyncio
@@ -461,34 +473,48 @@ Lower-level methods are available when a context manager does not fit:
461
473
  - `set(**kwargs)` returns the existing object or creates it. Whoever calls it takes over the cleanup that
462
474
  `scope()` does on exit and must call `clear()` when the object is no longer needed, if it ever is: a
463
475
  per-process client may live until the process ends;
464
- - `clear()` removes the object of the current scope and calls the destructor.
476
+ - `clear()` removes the object of the current scope and calls the destructor. Without a current scope it raises
477
+ like every other method, so call it where the scope exists: anywhere for `os.getpid`, inside the task for
478
+ `asyncio.current_task`, inside the block for a token scope.
465
479
 
466
- #### Scopes kept in a ContextVar
480
+ The `kwargs` of `scope()` and `set()` go to `create_func` only when the object is created; a call that joins an
481
+ existing object ignores them. `destructor_method_name` names a sync or async method of the object; `clear()`
482
+ removes the object from the registry first and then calls it once, and an exception from it propagates.
483
+ `registry` is the plain dict behind it, keyed by scope. One `asyncio.Lock` guards creation for all keys of a
484
+ registry, so a slow `create_func` in one scope delays first accesses in the others.
467
485
 
468
- A `scope_func` that declares a `token` parameter receives a freshly generated token when `scope()` is entered
469
- and `None` on every other access. This is for a scope of one execution (an HTTP request, an actor run) rather
470
- than one task: the function stores the token in a `ContextVar`, so coroutines spawned inside the block
471
- (`gather`, `TaskGroup`, `create_task`) inherit it and share the object with the parent, while outside of
472
- `scope()` there is no key and every method raises.
486
+ #### process_loop_scope
487
+
488
+ A ready-made key for clients that are pools bound to their event loop (`redis.asyncio`, `aiokafka`,
489
+ `aerospike_native`): `(os.getpid(), asyncio.get_running_loop())`. A second loop in the same process, a script
490
+ calling `asyncio.run` twice or a test suite, gets its own client instead of an "attached to a different loop"
491
+ error, and the pid guards a forked child, whose inherited sockets must not be reused. Raises `RuntimeError`
492
+ outside of a running loop.
473
493
 
474
494
  ```python
475
- from contextvars import ContextVar
495
+ from ddutils.scoped_registry import ScopedRegistry, process_loop_scope
496
+
497
+ redis_registry = ScopedRegistry(create_func=make_redis_client, scope_func=process_loop_scope, destructor_method_name='aclose')
498
+ ```
476
499
 
477
- execution_key: ContextVar[str | None] = ContextVar('execution_key', default=None)
500
+ #### execution_scope
478
501
 
502
+ A `scope_func` that declares a `token` parameter receives a freshly generated token when `scope()` is entered
503
+ or `set()` is called, and `None` on every other access (`get`, `clear`, a nested `scope()`); a scope started by
504
+ `set()` must be ended by `clear()`. This is for a scope of one execution (an HTTP request, an actor run) rather
505
+ than one task: the function stores the token in a `ContextVar`, so coroutines spawned inside the block
506
+ (`gather`, `TaskGroup`, `create_task`) inherit it and share the object with the parent, while outside of
507
+ `scope()` there is no key and every method raises. `execution_scope(name)` is that function, with its own
508
+ `ContextVar` named `name`, so every registry gets a scope of its own:
479
509
 
480
- def execution_scope(token: str | None) -> str | None:
481
- key = execution_key.get()
482
- if key is None and token is not None: # entering scope() outside of an execution: start one
483
- execution_key.set(token)
484
- key = token
485
- return key
510
+ ```python
511
+ from ddutils.scoped_registry import ScopedRegistry, execution_scope
486
512
 
487
513
 
488
514
  async def create_log_properties(**kwargs): ...
489
515
 
490
516
 
491
- log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope)
517
+ log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope('log_properties'))
492
518
 
493
519
 
494
520
  async def middleware(headers):
@@ -518,6 +544,11 @@ per task. The connections module adds two things on top:
518
544
  Databases with transactions pass their own `connection_manager_class`: a unit of work that begins, commits
519
545
  or rolls back and closes the session on exit. It depends on the driver, so it lives in the project.
520
546
 
547
+ The factory raises `ValueError` when `default` is not among the registries and `KeyError` for an unknown alias.
548
+ `ConnectionManager` enters with `registry.set()` and no arguments, so the `create_func` of its registries takes
549
+ none (use `functools.partial`). `close()` calls `clear()` on every registry, which needs a current scope: for
550
+ `process_loop_scope` that is inside the loop the clients were opened in, for example FastAPI's lifespan.
551
+
521
552
  ```python
522
553
  import os
523
554
  from enum import Enum
@@ -557,15 +588,24 @@ await clickhouse.close()
557
588
 
558
589
  `ddutils.feature_flags` is the storage-agnostic part of feature flags: `FeatureFlagRecord` (on or off, the proportion
559
590
  of readers that see it, a free-form payload), the `FeatureFlagStorage` interface and `FeatureFlags`, which reads
560
- through a storage with a per-process cache (`BASE_TTL` plus a random jitter). While the storage fails, the last
561
- known record is served and re-read with an exponential backoff from `ERROR_TTL` up to the TTL. The storages live
562
- with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`, `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
563
-
564
- Readers see booleans and payloads, not records. `is_enabled` is the flag's switch and its proportion in one answer:
565
- off for everyone when the flag is off, on for the `proportion` of the readers when it is on, so a kill-switch is a
566
- flag with proportion 1.0. With an `idempotent_key` (a user id, an account id) the split is repeatable, the same
567
- user always lands on the same side; without one it is random per call. `get_payload` is the payload as stored; its shape is the application's,
568
- parse it there.
591
+ through a storage with a cache. The storages live with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`,
592
+ `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
593
+
594
+ `FeatureFlagRecord(enabled=False, proportion=1.0, payload={})` is what a storage holds for one flag; a flag that
595
+ does not exist reads as these defaults. The record validates itself on construction: `enabled` takes a bool or
596
+ what a storage may hold for one (`1`, `'true'`, `'yes'`, `'on'`, `'t'`, `'y'` and their negations), `proportion`
597
+ a number in 0..1, `payload` a mapping, which is copied. `from_dict` builds a record from what a storage read and
598
+ rejects unknown keys; `to_dict` is the inverse.
599
+
600
+ Readers see booleans and payloads, not records. `is_enabled(name, idempotent_key=None)` is the flag's switch and
601
+ its proportion in one answer: off for everyone when the flag is off, on for the `proportion` of the readers when
602
+ it is on. The proportion applies whenever the flag is on, so a gradual rollout is written with an explicit
603
+ `proportion` and a kill-switch keeps the default. With an `idempotent_key` (anything with a `__str__`: a user id,
604
+ an account id) the split is repeatable, the same key always lands on the same side: the bucket is
605
+ `blake2b(f'{name}:{key}')` scaled to 0..1 and compared with the proportion, so the same key may be on one side for one
606
+ flag and on the other for another. Without a key the split is random per call. `get_payload(name)` is the payload
607
+ as stored, `{}` for a missing flag; its shape is the application's, parse it there and do not mutate it, it is
608
+ the cached object.
569
609
 
570
610
  ```python
571
611
  from ddredis.feature_flags import RedisFeatureFlagStorage
@@ -573,7 +613,7 @@ from ddutils.feature_flags import FeatureFlags
573
613
 
574
614
  feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
575
615
 
576
- # a kill-switch: proportion 1.0, on or off for everyone
616
+ # a kill-switch: the default proportion, on or off for everyone
577
617
  if await feature_flags.is_enabled('new_checkout'):
578
618
  ...
579
619
 
@@ -586,11 +626,18 @@ if await feature_flags.is_enabled('email_provider_block'):
586
626
  rules = EmailProviderBlockRules.model_validate(await feature_flags.get_payload('email_provider_block'))
587
627
  ```
588
628
 
589
- A storage implements `get`, `get_map`, `put` and `delete`; `rename` defaults to
590
- put-then-delete and is overridden where the storage can do it atomically. `FeatureFlagRecord` validates itself on
591
- construction; a storage builds it with `from_dict` and, when what it read is not a valid record, logs it and reads
592
- it as the defaults. A storage failure raises `FeatureFlagStorageError`
593
- with the cause chained.
629
+ `FeatureFlags(storage, base_ttl=BASE_TTL)` caches every flag it reads for `base_ttl` (15) plus 0 to `JITTER` (5)
630
+ seconds, so the readers of a process do not re-read at once. The cache belongs to the instance: keep one per
631
+ process, and expect a `put` to take up to a TTL to be seen, also from the process that wrote it. While the
632
+ storage fails, the last known record (or the defaults) is served and logged, and the re-read is retried with a
633
+ backoff from `ERROR_TTL` (1 second) doubling on every failure up to `base_ttl`.
634
+
635
+ A storage is a `FeatureFlagStorage` with `get(name) -> FeatureFlagRecord | None`, `get_map() -> dict[str, FeatureFlagRecord]`,
636
+ `put(name, record) -> None` (create or overwrite; there is no create-only) and `delete(name) -> bool`;
637
+ `rename(old_name, new_name, record)` defaults to put-then-delete and is overridden where the storage can do it
638
+ atomically. A storage builds records with `from_dict` and, when what it read is not a valid record, logs it and
639
+ reads it as the defaults. Only a failure of the storage itself raises, as `FeatureFlagStorageError` with the cause
640
+ chained.
594
641
 
595
642
  ## Context Helpers
596
643
 
@@ -613,8 +660,16 @@ AST-based introspection for extracting exceptions from function source code.
613
660
 
614
661
  ### extract_function_exceptions
615
662
 
616
- Parses a function’s source code to find all `raise` statements and identify the exception types they use.
617
- Returns an iterator of `ExceptionInfo` objects describing each raised exception.
663
+ Parses a function’s source code to find all `raise` statements and identify the exception types they use.
664
+ Returns an iterator of `ExceptionInfo` objects describing each raised exception: `exception_class`, the
665
+ positional `args` and keyword `kwargs` of the `raise` as written, with any non-literal argument replaced by
666
+ `UNDEFINED_VALUE`. `get_kwargs()` maps them onto the parameters of the exception's `__init__`, filling in
667
+ defaults and class attributes; `get_exception_instance(dry_run=True)` builds the exception from them, with
668
+ `'<name>'` for undefined values, and returns `None` instead of raising when `dry_run`.
669
+
670
+ The function needs its source (`inspect.getsource`), so it does not work on builtins or code without a file.
671
+ A bare `raise` or `raise err` of a caught variable is skipped, an exception class that cannot be resolved by name
672
+ in the function's module or `builtins` is skipped too; `raise self.Error()` is not supported and raises `ValueError`.
618
673
 
619
674
  ## Value Helpers
620
675
 
@@ -9,7 +9,7 @@ from typing import Any, NamedTuple, Protocol, Self
9
9
 
10
10
  logger = logging.getLogger(__name__)
11
11
 
12
- DEFAULT_PROPORTION = 0.01
12
+ DEFAULT_PROPORTION = 1.0 # a record without a proportion is on for everyone when enabled
13
13
 
14
14
  BASE_TTL = 15 # seconds a record is served from the cache before it is re-read
15
15
  JITTER = 5 # seconds added at random to the TTL, so the readers of a process do not re-read at once
@@ -133,7 +133,7 @@ class _CacheEntry(NamedTuple):
133
133
 
134
134
  class FeatureFlags:
135
135
  """
136
- Feature flags read through a `FeatureFlagStorage`, with a per-process cache.
136
+ Feature flags read through a `FeatureFlagStorage`, with a cache per instance: keep one instance per process.
137
137
 
138
138
  Each flag is on or off, has a proportion for gradual rollouts and a payload for arbitrary data. Records are
139
139
  cached for `base_ttl` plus a random jitter so the storage is not read on every call. While the storage
@@ -141,7 +141,7 @@ class FeatureFlags:
141
141
  and then with an exponential backoff up to `base_ttl`.
142
142
 
143
143
  `is_enabled` is the flag's switch and its proportion in one answer: off for everyone when the flag is off,
144
- on for the `proportion` of the readers when it is on (a kill-switch is a flag with proportion 1.0). With an
144
+ on for the `proportion` of the readers when it is on (a kill-switch keeps the default proportion, 1.0). With an
145
145
  `idempotent_key` (a user id, an account id) the split is repeatable: every call with the same key lands on
146
146
  the same side, so a rollout is a consistent group. Without one it is random per call.
147
147
  `get_payload` is the flag's payload as stored; its shape is the application's business, parse it there.
@@ -149,7 +149,7 @@ class FeatureFlags:
149
149
  Example:
150
150
  feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
151
151
 
152
- if await feature_flags.is_enabled('new_checkout'): # proportion 1.0: on or off for everyone
152
+ if await feature_flags.is_enabled('new_checkout'): # default proportion: on or off for everyone
153
153
  ...
154
154
  if await feature_flags.is_enabled('new_ranking', user_id): # on for `proportion` of the users
155
155
  ...
@@ -10,10 +10,10 @@ def get_module(module: ModuleType, sub_modules: list[str]) -> ModuleType:
10
10
  if len(sub_modules) == 0:
11
11
  return module
12
12
 
13
- sub_module = sub_modules.pop(0)
13
+ sub_module, *rest = sub_modules
14
14
 
15
15
  if hasattr(module, sub_module):
16
16
  module = getattr(module, sub_module)
17
- return get_module(module, sub_modules)
17
+ return get_module(module, rest)
18
18
  else:
19
19
  raise ValueError(f'Module {sub_module} not found in {module.__name__}')
@@ -0,0 +1,127 @@
1
+ import logging
2
+ from collections.abc import Callable, Coroutine
3
+ from functools import wraps
4
+ from inspect import iscoroutinefunction
5
+ from typing import Any, Generic, Never, ParamSpec, TypeVar, overload
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ P = ParamSpec('P')
10
+ R = TypeVar('R')
11
+ D = TypeVar('D')
12
+
13
+
14
+ class _NotSet:
15
+ def __repr__(self) -> str:
16
+ return 'NOT_SET'
17
+
18
+
19
+ # `default_result` left at NOT_SET means "there is no fallback": the last error propagates
20
+ NOT_SET = _NotSet()
21
+
22
+
23
+ class _SafeCall(Generic[D]):
24
+ """
25
+ The decorator `safe_call(...)` returns: calls the function up to `1 + retries` times and, when every attempt
26
+ fails with one of `exceptions`, returns `default_result` or re-raises the last error if none was given.
27
+ """
28
+
29
+ def __init__(
30
+ self, retries: int, default_result: D | _NotSet, capture_exception: bool, exceptions: tuple[type[Exception], ...]
31
+ ) -> None:
32
+ if retries < 0:
33
+ raise ValueError(f'retries must be non-negative, got {retries!r}')
34
+ self.retries = retries
35
+ self.default_result = default_result
36
+ self.capture_exception = capture_exception
37
+ self.exceptions = exceptions
38
+
39
+ def _handle(self, error: BaseException, attempt: int) -> None:
40
+ """Logs a failed attempt, or re-raises when it was the last one and there is no fallback."""
41
+ if attempt == self.retries and isinstance(self.default_result, _NotSet):
42
+ raise error
43
+ if self.capture_exception:
44
+ logger.exception(error)
45
+
46
+ # `self` is annotated explicitly: without it ty does not substitute `D` in the overloads.
47
+ # The coroutine overload goes first: `Callable[P, R]` matches a coroutine function too (with R the coroutine),
48
+ # and the checker takes the first overload that fits.
49
+ @overload
50
+ def __call__(
51
+ self: '_SafeCall[D]', func: Callable[P, Coroutine[Any, Any, R]]
52
+ ) -> Callable[P, Coroutine[Any, Any, R | D]]: ...
53
+
54
+ @overload
55
+ def __call__(self: '_SafeCall[D]', func: Callable[P, R]) -> Callable[P, R | D]: ...
56
+
57
+ def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
58
+ if iscoroutinefunction(func):
59
+
60
+ @wraps(func)
61
+ async def async_wrapped_func(*args: Any, **kwargs: Any) -> Any:
62
+ for attempt in range(self.retries + 1):
63
+ try:
64
+ return await func(*args, **kwargs)
65
+ except self.exceptions as error:
66
+ self._handle(error, attempt)
67
+ return self.default_result
68
+
69
+ return async_wrapped_func
70
+
71
+ @wraps(func)
72
+ def wrapped_func(*args: Any, **kwargs: Any) -> Any:
73
+ for attempt in range(self.retries + 1):
74
+ try:
75
+ return func(*args, **kwargs)
76
+ except self.exceptions as error:
77
+ self._handle(error, attempt)
78
+ return self.default_result
79
+
80
+ return wrapped_func
81
+
82
+
83
+ @overload
84
+ def safe_call(
85
+ *, retries: int = 0, capture_exception: bool = True, exceptions: tuple[type[Exception], ...] = (Exception,)
86
+ ) -> _SafeCall[Never]: ...
87
+
88
+
89
+ @overload
90
+ def safe_call(
91
+ *,
92
+ default_result: D,
93
+ retries: int = 0,
94
+ capture_exception: bool = True,
95
+ exceptions: tuple[type[Exception], ...] = (Exception,),
96
+ ) -> _SafeCall[D]: ...
97
+
98
+
99
+ def safe_call(
100
+ *,
101
+ default_result: Any = NOT_SET,
102
+ retries: int = 0,
103
+ capture_exception: bool = True,
104
+ exceptions: tuple[type[Exception], ...] = (Exception,),
105
+ ) -> _SafeCall[Any]:
106
+ """
107
+ Decorator that retries a failing call and then falls back to `default_result` or re-raises.
108
+
109
+ The function is called up to `1 + retries` times; an attempt counts as failed when it raises one of
110
+ `exceptions`. Every failure that is retried or replaced by `default_result` is logged with the traceback
111
+ (`capture_exception`). Without a `default_result` the last error propagates, so a `None` result always means
112
+ the function returned `None`, never that an error was swallowed.
113
+
114
+ A coroutine function is awaited inside the decorator, so the exceptions raised while awaiting are the ones
115
+ handled; the result is again a coroutine function.
116
+
117
+ Example:
118
+ @safe_call(default_result=None, exceptions=(RedisError,), capture_exception=False)
119
+ async def get_cached_profile(profile_id: int) -> Profile | None: ... # None when Redis is down
120
+
121
+ @safe_call(retries=1, exceptions=(ConnectionError,))
122
+ def fetch(url: str) -> Response: ... # one more try on a dropped connection, then the error
123
+ """
124
+ return _SafeCall(retries, default_result, capture_exception, exceptions)
125
+
126
+
127
+ __all__ = ('NOT_SET', 'safe_call')
@@ -1,7 +1,9 @@
1
1
  import asyncio
2
2
  import inspect
3
+ import os
3
4
  from collections.abc import AsyncIterator, Awaitable, Callable, Hashable
4
5
  from contextlib import asynccontextmanager
6
+ from contextvars import ContextVar
5
7
  from typing import Any, Generic, TypeVar, get_args
6
8
  from uuid import uuid4
7
9
 
@@ -125,3 +127,40 @@ class ScopedRegistry(Generic[_T]):
125
127
  finally:
126
128
  if created:
127
129
  await self.clear()
130
+
131
+
132
+ def process_loop_scope() -> tuple[int, asyncio.AbstractEventLoop]:
133
+ """
134
+ Scope key for a client bound to its event loop (`redis.asyncio`, `aiokafka`, `aerospike_native`): one value per
135
+ process and running loop. A second loop in the same process (a script calling `asyncio.run` twice, a test
136
+ suite) gets its own client instead of an "attached to a different loop" error, and the pid guards a forked
137
+ child, whose inherited sockets must not be reused. Raises `RuntimeError` outside of a running loop.
138
+ """
139
+ return os.getpid(), asyncio.get_running_loop()
140
+
141
+
142
+ def execution_scope(name: str) -> Callable[[str | None], str | None]:
143
+ """
144
+ A scope key for one execution (an HTTP request, an actor run) rather than one task, kept in a `ContextVar`
145
+ named `name`: the key planted on entering `scope()` is inherited by the coroutines spawned inside the block
146
+ (`gather`, `TaskGroup`, `create_task`), so they share the value with the parent. Reads never start a scope,
147
+ outside of `scope()` there is no key and the registry raises. One `ContextVar` per call, so every registry
148
+ gets its own scope function.
149
+
150
+ The key is not reset when the block ends, so `scope()` must be entered in a task that does not outlive the
151
+ block (a request handler, an actor run); a key left in a long-living task would be inherited by every task
152
+ spawned from it afterwards.
153
+ """
154
+ execution_key: ContextVar[str | None] = ContextVar(name, default=None)
155
+
156
+ def scope_func(token: str | None) -> str | None:
157
+ key = execution_key.get()
158
+ if key is None and token is not None: # entering `scope()` outside of an execution: start one
159
+ execution_key.set(token)
160
+ key = token
161
+ return key
162
+
163
+ return scope_func
164
+
165
+
166
+ __all__ = ('SCOPE_TOKEN_PARAMETER', 'ScopedRegistry', 'execution_scope', 'process_loop_scope')
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "ddutils"
3
3
  description = "Domain Driven Utils Library"
4
- version = "0.3.3"
4
+ version = "0.4.0"
5
5
  license = "MIT"
6
6
  license-files = ["LICENSE"]
7
7
  readme = "README.md"
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "ddutils"
3
3
  description = "Domain Driven Utils Library"
4
- version = "0.3.3"
4
+ version = "0.4.0"
5
5
  authors = [{ name = "davyddd" }]
6
6
  license = "MIT"
7
7
  license-files = ["LICENSE"]
@@ -1,51 +0,0 @@
1
- import logging
2
- from collections.abc import Callable
3
- from functools import wraps
4
- from typing import Any
5
-
6
- logger = logging.getLogger(__name__)
7
-
8
-
9
- def safe_call(
10
- func: Callable | None = None,
11
- capture_exception: bool = True,
12
- default_result: Any | None = None,
13
- exceptions: tuple[type[Exception], ...] = (Exception,),
14
- ) -> Callable:
15
- if func is None:
16
- return lambda _func: safe_call(
17
- func=_func, capture_exception=capture_exception, default_result=default_result, exceptions=exceptions
18
- )
19
-
20
- @wraps(func)
21
- def wrapped_func(*args, **kwargs):
22
- try:
23
- result = func(*args, **kwargs)
24
- except exceptions as error:
25
- if capture_exception:
26
- logger.exception(error)
27
-
28
- result = default_result
29
-
30
- return result
31
-
32
- return wrapped_func
33
-
34
-
35
- def retry_once_after_exception(
36
- func: Callable | None = None, capture_exception: bool = True, exceptions: tuple[type[Exception], ...] = (Exception,)
37
- ) -> Callable:
38
- if func is None:
39
- return lambda _func: retry_once_after_exception(func=_func, capture_exception=capture_exception, exceptions=exceptions)
40
-
41
- @wraps(func)
42
- def wrapped_func(*args, **kwargs):
43
- try:
44
- return func(*args, **kwargs)
45
- except exceptions as error:
46
- if capture_exception:
47
- logger.exception(error)
48
-
49
- return func(*args, **kwargs)
50
-
51
- return wrapped_func
File without changes
File without changes
File without changes
File without changes
File without changes