ddutils 0.3.3__tar.gz → 0.4.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.
@@ -1,4 +1,22 @@
1
- # DDUtils
1
+ Metadata-Version: 2.4
2
+ Name: ddutils
3
+ Version: 0.4.1
4
+ Summary: Shared utilities of the dd libraries: annotation and class helpers, convertors, scoped registries, connection factories and feature flags
5
+ Keywords: python,ddutils,utils,helpers,type hints,type annotations,introspection,generics,scoped registry,context scope,connection manager,connection factory,feature flags,feature toggle,retry,safe call,decorators,convertors,asyncio
6
+ Author: davyddd
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.11, <3.15
16
+ Project-URL: Repository, https://github.com/davyddd/ddutils
17
+ Description-Content-Type: text/markdown
18
+
19
+ # ddutils
2
20
 
3
21
  [![pypi](https://img.shields.io/pypi/v/ddutils.svg)](https://pypi.python.org/pypi/ddutils)
4
22
  [![downloads](https://static.pepy.tech/badge/ddutils/month)](https://pepy.tech/project/ddutils)
@@ -6,8 +24,7 @@
6
24
  [![codecov](https://codecov.io/gh/davyddd/ddutils/branch/main/graph/badge.svg)](https://app.codecov.io/github/davyddd/ddutils)
7
25
  [![license](https://img.shields.io/github/license/davyddd/ddutils.svg)](https://github.com/davyddd/ddutils/blob/main/LICENSE)
8
26
 
9
- **DDUtils** is a lightweight Python library that provides helper functions and decorators for common programming tasks.
10
- It focuses on type safety, robustness, and runtime introspection — all without external dependencies.
27
+ Shared utilities of the dd libraries: annotation and class helpers, convertors, scoped registries, connection factories and feature flags
11
28
 
12
29
  ## Installation
13
30
 
@@ -31,11 +48,24 @@ fab bash # bash inside the container
31
48
  This project was generated from [dd-lib-stub](https://github.com/davyddd/dd-lib-stub);
32
49
  run `uvx copier update` to pull in template updates.
33
50
 
51
+ ## Compatibility
52
+
53
+ Python 3.11 to 3.14. What changed in each release, breaking changes included,
54
+ is in the [GitHub releases](https://github.com/davyddd/ddutils/releases).
55
+
56
+ <!-- The sections below are the library's own; copier update leaves them alone -->
57
+
58
+ No runtime dependencies. The tests need no external services.
59
+
34
60
  ## Type Annotation Helpers
35
61
 
36
62
  Utilities for inspecting and working with Python type hints and generic types.
37
63
  These helpers let you analyze and modify complex annotations at runtime.
38
64
 
65
+ They work on classes and parametrized generics (`list[int]`, `Dict[str, int]`, a `NewType`). A union, `Optional`
66
+ included, a `Literal`, a `TypeVar`, `Any` or a string annotation is not a type and raises `TypeError` rather than
67
+ returning `False`; strip the `Optional` with [get_annotation_without_optional](#get_annotation_without_optional) first.
68
+
39
69
  ### get_annotation_origin
40
70
 
41
71
  Returns the base (origin) type of a generic annotation, unwrapping `NewType` and handling generic aliases recursively.
@@ -89,7 +119,7 @@ is_complex_sequence(dict) # False
89
119
  ### get_complex_sequence_element_annotation
90
120
 
91
121
  Returns the element type from a sequence annotation.
92
- Raises `ValueError` if the annotation doesn’t specify an element type.
122
+ Raises `ValueError` if the annotation is not a complex sequence or doesn’t specify an element type.
93
123
 
94
124
  ```python
95
125
  from typing import List, Set
@@ -102,7 +132,8 @@ get_complex_sequence_element_annotation(Set[str]) # <class 'str'>
102
132
 
103
133
  ### get_dict_items_annotation
104
134
 
105
- Returns the key and value types from a dictionary annotation.
135
+ Returns the key and value types from a dictionary annotation. Raises `TypeError` for an annotation that is not a
136
+ `dict`, `ValueError` for a bare `dict` without arguments.
106
137
 
107
138
  ```python
108
139
  from typing import Dict
@@ -149,7 +180,8 @@ Helper functions for inspecting and extending class-level behavior
149
180
  ### classproperty
150
181
 
151
182
  Works like `@property`, but for class attributes.
152
- Can be accessed as `ClassName.property_name` without creating an instance.
183
+ Can be accessed as `ClassName.property_name` without creating an instance. Read-only in the sense that there is
184
+ no setter: assigning to the attribute replaces the descriptor on the class.
153
185
 
154
186
  ```python
155
187
  from ddutils.class_helpers import classproperty
@@ -198,7 +230,8 @@ get_origin_class_of_method(B, 'method') # <class 'A'>
198
230
  ### get_generic_base_argument
199
231
 
200
232
  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.
233
+ subscripted, the `TypeVar` itself when the subclass is still generic. `position` picks the argument of a base
234
+ with several type parameters (default `0`).
202
235
 
203
236
  ```python
204
237
  from typing import Generic, TypeVar
@@ -222,9 +255,11 @@ get_generic_base_argument(Repository, Repository) # None
222
255
 
223
256
  ### require_class_attribute
224
257
 
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.
258
+ `require_class_attribute(cls, name, expected_type=None, *, allow_empty=False)` returns a class attribute that
259
+ subclasses are expected to declare, for `__init_subclass__` checks. A missing, `None` or empty value raises
260
+ `AttributeError`, a value that is not an instance of `expected_type` (a class or a tuple of classes, skipped when
261
+ `None`) raises `TypeError`; both name the attribute and the class, so a misconfigured subclass fails at definition
262
+ rather than on first use. `allow_empty=True` accepts `''`, `[]` or `{}`; numbers are never empty, `0` passes.
228
263
 
229
264
  ```python
230
265
  from typing import ClassVar
@@ -256,8 +291,10 @@ Tools for creating and modifying Python functions at runtime.
256
291
 
257
292
  ### create_new_function
258
293
 
259
- Creates a new function from an existing one, with an optional new name.
260
- Preserves default values and closures.
294
+ Creates a new function from an existing one, with an optional new name, by rebuilding its code object. It keeps
295
+ the code, globals and positional defaults (`__defaults__`); closure cells are copied as a snapshot of their
296
+ current values, so the copy does not follow later changes to the enclosed variables. Keyword-only defaults,
297
+ annotations, the docstring and `__qualname__` are not carried over.
261
298
 
262
299
  ```python
263
300
  from ddutils.function_helpers import create_new_function
@@ -355,44 +392,37 @@ Utilities for working with dates and times.
355
392
 
356
393
  ### utc_now
357
394
 
358
- Returns the current datetime in UTC timezone.
395
+ `utc_now() -> datetime`: the current time as an aware `datetime`, `datetime.now(tz=UTC)`.
359
396
 
360
397
  ## Safe Decorators
361
398
 
362
- Decorators that help functions fail safely and handle exceptions gracefully.
363
-
364
399
  ### safe_call
365
400
 
366
- Wraps a function to catch exceptions and return a default value instead of raising errors.
401
+ Retries a failing call and then falls back to a default or re-raises. The function runs up to `1 + retries`
402
+ times; an attempt fails when it raises one of `exceptions`. Without `default_result` the last error propagates,
403
+ so a `None` result always means the function returned `None`, never that an error was swallowed. Every failure
404
+ that is retried or replaced by the default is logged with its traceback unless `capture_exception=False`.
405
+ Coroutine functions are awaited inside the decorator, so the exceptions raised while awaiting are the ones handled.
367
406
 
368
407
  ```python
369
408
  import requests
409
+ from redis.exceptions import RedisError
370
410
  from ddutils.safe_decorators import safe_call
371
411
 
372
412
 
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
-
413
+ @safe_call(default_result=0)
414
+ def count_pending() -> int:
415
+ return requests.get('https://api.example.com/pending').json()['count'] # 0 on any error
378
416
 
379
- @safe_call(default_result=0, exceptions=(ValueError,))
380
- def convert_to_int(value):
381
- return int(value)
382
- ```
383
417
 
384
- ### retry_once_after_exception
418
+ @safe_call(retries=1, exceptions=(requests.ConnectionError,))
419
+ def fetch_report(url: str) -> requests.Response:
420
+ return requests.get(url) # one more try on a dropped connection, then the error
385
421
 
386
- Retries a function once if it raises an exception.
387
422
 
388
- ```python
389
- import requests
390
- from ddutils.safe_decorators import retry_once_after_exception
391
-
392
-
393
- @retry_once_after_exception
394
- def unstable_network_call():
395
- return requests.get('https://api.example.com/unstable')
423
+ @safe_call(default_result=None, exceptions=(RedisError,), capture_exception=False)
424
+ async def get_cached_profile(profile_id: int) -> Profile | None:
425
+ return await cache.get(profile_id) # None when Redis is unavailable
396
426
  ```
397
427
 
398
428
  ## Module and Object Management
@@ -401,7 +431,8 @@ Helpers for importing and accessing modules or objects at runtime.
401
431
 
402
432
  ### get_module
403
433
 
404
- Finds a nested module by path within a parent module.
434
+ Finds a nested module by path within a parent module. Raises `ValueError` when a step of the path is not an
435
+ attribute of the module reached so far.
405
436
 
406
437
  ```python
407
438
  import os
@@ -413,7 +444,8 @@ get_module(os, ['path']) # <module 'os.path'>
413
444
 
414
445
  ### get_object_by_path
415
446
 
416
- Imports and returns an object by its full dotted path (e.g. 'json.loads').
447
+ Imports and returns an object by its full dotted path (e.g. 'json.loads'). Returns `None` instead of raising when
448
+ the path is not a string, the module cannot be imported or the attribute does not exist.
417
449
 
418
450
  ```python
419
451
  from ddutils.object_getter import get_object_by_path
@@ -428,12 +460,13 @@ A registry that keeps one object instance per scope and manages its lifetime.
428
460
 
429
461
  ### ScopedRegistry
430
462
 
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`.
463
+ `ScopedRegistry(create_func, scope_func, destructor_method_name=None)` keeps one object per scope. `scope_func`
464
+ decides what the current scope is and returns its key; `None` means "no current scope" and makes every method
465
+ raise `RuntimeError`, as does a key that is not hashable. `asyncio.current_task` as the key needs a running loop.
433
466
 
434
467
  `scope()` is the entry point into a scope: it creates the object on enter and removes it on exit, calling
435
468
  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.
469
+ Concurrent first accesses with the same key call `create_func` only once; `create_func` may be sync or async.
437
470
 
438
471
  ```python
439
472
  import asyncio
@@ -461,34 +494,48 @@ Lower-level methods are available when a context manager does not fit:
461
494
  - `set(**kwargs)` returns the existing object or creates it. Whoever calls it takes over the cleanup that
462
495
  `scope()` does on exit and must call `clear()` when the object is no longer needed, if it ever is: a
463
496
  per-process client may live until the process ends;
464
- - `clear()` removes the object of the current scope and calls the destructor.
497
+ - `clear()` removes the object of the current scope and calls the destructor. Without a current scope it raises
498
+ like every other method, so call it where the scope exists: anywhere for `os.getpid`, inside the task for
499
+ `asyncio.current_task`, inside the block for a token scope.
465
500
 
466
- #### Scopes kept in a ContextVar
501
+ The `kwargs` of `scope()` and `set()` go to `create_func` only when the object is created; a call that joins an
502
+ existing object ignores them. `destructor_method_name` names a sync or async method of the object; `clear()`
503
+ removes the object from the registry first and then calls it once, and an exception from it propagates.
504
+ `registry` is the plain dict behind it, keyed by scope. One `asyncio.Lock` guards creation for all keys of a
505
+ registry, so a slow `create_func` in one scope delays first accesses in the others.
467
506
 
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.
507
+ #### process_loop_scope
508
+
509
+ A ready-made key for clients that are pools bound to their event loop (`redis.asyncio`, `aiokafka`,
510
+ `aerospike_native`): `(os.getpid(), asyncio.get_running_loop())`. A second loop in the same process, a script
511
+ calling `asyncio.run` twice or a test suite, gets its own client instead of an "attached to a different loop"
512
+ error, and the pid guards a forked child, whose inherited sockets must not be reused. Raises `RuntimeError`
513
+ outside of a running loop.
473
514
 
474
515
  ```python
475
- from contextvars import ContextVar
516
+ from ddutils.scoped_registry import ScopedRegistry, process_loop_scope
476
517
 
477
- execution_key: ContextVar[str | None] = ContextVar('execution_key', default=None)
518
+ redis_registry = ScopedRegistry(create_func=make_redis_client, scope_func=process_loop_scope, destructor_method_name='aclose')
519
+ ```
478
520
 
521
+ #### execution_scope
479
522
 
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
523
+ A `scope_func` that declares a `token` parameter receives a freshly generated token when `scope()` is entered
524
+ or `set()` is called, and `None` on every other access (`get`, `clear`, a nested `scope()`); a scope started by
525
+ `set()` must be ended by `clear()`. This is for a scope of one execution (an HTTP request, an actor run) rather
526
+ than one task: the function stores the token in a `ContextVar`, so coroutines spawned inside the block
527
+ (`gather`, `TaskGroup`, `create_task`) inherit it and share the object with the parent, while outside of
528
+ `scope()` there is no key and every method raises. `execution_scope(name)` is that function, with its own
529
+ `ContextVar` named `name`, so every registry gets a scope of its own:
530
+
531
+ ```python
532
+ from ddutils.scoped_registry import ScopedRegistry, execution_scope
486
533
 
487
534
 
488
535
  async def create_log_properties(**kwargs): ...
489
536
 
490
537
 
491
- log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope)
538
+ log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope('log_properties'))
492
539
 
493
540
 
494
541
  async def middleware(headers):
@@ -518,6 +565,11 @@ per task. The connections module adds two things on top:
518
565
  Databases with transactions pass their own `connection_manager_class`: a unit of work that begins, commits
519
566
  or rolls back and closes the session on exit. It depends on the driver, so it lives in the project.
520
567
 
568
+ The factory raises `ValueError` when `default` is not among the registries and `KeyError` for an unknown alias.
569
+ `ConnectionManager` enters with `registry.set()` and no arguments, so the `create_func` of its registries takes
570
+ none (use `functools.partial`). `close()` calls `clear()` on every registry, which needs a current scope: for
571
+ `process_loop_scope` that is inside the loop the clients were opened in, for example FastAPI's lifespan.
572
+
521
573
  ```python
522
574
  import os
523
575
  from enum import Enum
@@ -553,19 +605,46 @@ async with atomic(alias=PostgresDB.REPLICA) as session:
553
605
  await clickhouse.close()
554
606
  ```
555
607
 
608
+ ### connection_proxy
609
+
610
+ Some libraries want a connection object at construction and keep it for the life of the process: a rate limiter's
611
+ bucket, a lock implementation. `connection_proxy(factory, *, alias=None)` returns a `ConnectionProxy` typed as the
612
+ connection it stands in for; every method call borrows the connection from the factory for that one call and keeps
613
+ nothing of it, the way a ddsql adapter or a ddredis lock does by hand. A sync method is called inside the borrow as
614
+ well and its result returned as is.
615
+
616
+ ```python
617
+ from ddutils.connections import connection_proxy
618
+
619
+ bucket = await RedisBucket.init(rates, redis=connection_proxy(redis_client_factory), bucket_key='api')
620
+ ```
621
+
622
+ Only method calls are proxied: attributes and properties of the connection cannot be reached, since attribute
623
+ access cannot borrow. A sync method whose result stays bound to the connection (a pipeline) is safe only with a
624
+ manager that releases nothing on exit, such as `ConnectionManager`.
625
+
556
626
  ## Feature Flags
557
627
 
558
628
  `ddutils.feature_flags` is the storage-agnostic part of feature flags: `FeatureFlagRecord` (on or off, the proportion
559
629
  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.
630
+ through a storage with a cache. The storages live with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`,
631
+ `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
632
+
633
+ `FeatureFlagRecord(enabled=False, proportion=1.0, payload={})` is what a storage holds for one flag; a flag that
634
+ does not exist reads as these defaults. The record validates itself on construction: `enabled` takes a bool or
635
+ what a storage may hold for one (`1`, `'true'`, `'yes'`, `'on'`, `'t'`, `'y'` and their negations), `proportion`
636
+ a number in 0..1, `payload` a mapping, which is copied. `from_dict` builds a record from what a storage read and
637
+ rejects unknown keys; `to_dict` is the inverse.
638
+
639
+ Readers see booleans and payloads, not records. `is_enabled(name, idempotent_key=None)` is the flag's switch and
640
+ its proportion in one answer: off for everyone when the flag is off, on for the `proportion` of the readers when
641
+ it is on. The proportion applies whenever the flag is on, so a gradual rollout is written with an explicit
642
+ `proportion` and a kill-switch keeps the default. With an `idempotent_key` (anything with a `__str__`: a user id,
643
+ an account id) the split is repeatable, the same key always lands on the same side: the bucket is
644
+ `blake2b(f'{name}:{key}')` scaled to 0..1 and compared with the proportion, so the same key may be on one side for one
645
+ flag and on the other for another. Without a key the split is random per call. `get_payload(name)` is the payload
646
+ as stored, `{}` for a missing flag; its shape is the application's, parse it there and do not mutate it, it is
647
+ the cached object.
569
648
 
570
649
  ```python
571
650
  from ddredis.feature_flags import RedisFeatureFlagStorage
@@ -573,7 +652,7 @@ from ddutils.feature_flags import FeatureFlags
573
652
 
574
653
  feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
575
654
 
576
- # a kill-switch: proportion 1.0, on or off for everyone
655
+ # a kill-switch: the default proportion, on or off for everyone
577
656
  if await feature_flags.is_enabled('new_checkout'):
578
657
  ...
579
658
 
@@ -586,11 +665,18 @@ if await feature_flags.is_enabled('email_provider_block'):
586
665
  rules = EmailProviderBlockRules.model_validate(await feature_flags.get_payload('email_provider_block'))
587
666
  ```
588
667
 
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.
668
+ `FeatureFlags(storage, base_ttl=BASE_TTL)` caches every flag it reads for `base_ttl` (15) plus 0 to `JITTER` (5)
669
+ seconds, so the readers of a process do not re-read at once. The cache belongs to the instance: keep one per
670
+ process, and expect a `put` to take up to a TTL to be seen, also from the process that wrote it. While the
671
+ storage fails, the last known record (or the defaults) is served and logged, and the re-read is retried with a
672
+ backoff from `ERROR_TTL` (1 second) doubling on every failure up to `base_ttl`.
673
+
674
+ A storage is a `FeatureFlagStorage` with `get(name) -> FeatureFlagRecord | None`, `get_map() -> dict[str, FeatureFlagRecord]`,
675
+ `put(name, record) -> None` (create or overwrite; there is no create-only) and `delete(name) -> bool`;
676
+ `rename(old_name, new_name, record)` defaults to put-then-delete and is overridden where the storage can do it
677
+ atomically. A storage builds records with `from_dict` and, when what it read is not a valid record, logs it and
678
+ reads it as the defaults. Only a failure of the storage itself raises, as `FeatureFlagStorageError` with the cause
679
+ chained.
594
680
 
595
681
  ## Context Helpers
596
682
 
@@ -613,8 +699,16 @@ AST-based introspection for extracting exceptions from function source code.
613
699
 
614
700
  ### extract_function_exceptions
615
701
 
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.
702
+ Parses a function’s source code to find all `raise` statements and identify the exception types they use.
703
+ Returns an iterator of `ExceptionInfo` objects describing each raised exception: `exception_class`, the
704
+ positional `args` and keyword `kwargs` of the `raise` as written, with any non-literal argument replaced by
705
+ `UNDEFINED_VALUE`. `get_kwargs()` maps them onto the parameters of the exception's `__init__`, filling in
706
+ defaults and class attributes; `get_exception_instance(dry_run=True)` builds the exception from them, with
707
+ `'<name>'` for undefined values, and returns `None` instead of raising when `dry_run`.
708
+
709
+ The function needs its source (`inspect.getsource`), so it does not work on builtins or code without a file.
710
+ A bare `raise` or `raise err` of a caught variable is skipped, an exception class that cannot be resolved by name
711
+ in the function's module or `builtins` is skipped too; `raise self.Error()` is not supported and raises `ValueError`.
618
712
 
619
713
  ## Value Helpers
620
714
 
@@ -1,22 +1,4 @@
1
- Metadata-Version: 2.4
2
- Name: ddutils
3
- Version: 0.3.3
4
- Summary: Domain Driven Utils Library
5
- Keywords: python,ddutils
6
- Author: davyddd
7
- License-Expression: MIT
8
- License-File: LICENSE
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Programming Language :: Python :: 3.11
11
- Classifier: Programming Language :: Python :: 3.12
12
- Classifier: Programming Language :: Python :: 3.13
13
- Classifier: Programming Language :: Python :: 3.14
14
- Classifier: Typing :: Typed
15
- Requires-Python: >=3.11, <3.15
16
- Project-URL: Repository, https://github.com/davyddd/ddutils
17
- Description-Content-Type: text/markdown
18
-
19
- # DDUtils
1
+ # ddutils
20
2
 
21
3
  [![pypi](https://img.shields.io/pypi/v/ddutils.svg)](https://pypi.python.org/pypi/ddutils)
22
4
  [![downloads](https://static.pepy.tech/badge/ddutils/month)](https://pepy.tech/project/ddutils)
@@ -24,8 +6,7 @@ Description-Content-Type: text/markdown
24
6
  [![codecov](https://codecov.io/gh/davyddd/ddutils/branch/main/graph/badge.svg)](https://app.codecov.io/github/davyddd/ddutils)
25
7
  [![license](https://img.shields.io/github/license/davyddd/ddutils.svg)](https://github.com/davyddd/ddutils/blob/main/LICENSE)
26
8
 
27
- **DDUtils** is a lightweight Python library that provides helper functions and decorators for common programming tasks.
28
- It focuses on type safety, robustness, and runtime introspection — all without external dependencies.
9
+ Shared utilities of the dd libraries: annotation and class helpers, convertors, scoped registries, connection factories and feature flags
29
10
 
30
11
  ## Installation
31
12
 
@@ -49,11 +30,24 @@ fab bash # bash inside the container
49
30
  This project was generated from [dd-lib-stub](https://github.com/davyddd/dd-lib-stub);
50
31
  run `uvx copier update` to pull in template updates.
51
32
 
33
+ ## Compatibility
34
+
35
+ Python 3.11 to 3.14. What changed in each release, breaking changes included,
36
+ is in the [GitHub releases](https://github.com/davyddd/ddutils/releases).
37
+
38
+ <!-- The sections below are the library's own; copier update leaves them alone -->
39
+
40
+ No runtime dependencies. The tests need no external services.
41
+
52
42
  ## Type Annotation Helpers
53
43
 
54
44
  Utilities for inspecting and working with Python type hints and generic types.
55
45
  These helpers let you analyze and modify complex annotations at runtime.
56
46
 
47
+ They work on classes and parametrized generics (`list[int]`, `Dict[str, int]`, a `NewType`). A union, `Optional`
48
+ included, a `Literal`, a `TypeVar`, `Any` or a string annotation is not a type and raises `TypeError` rather than
49
+ returning `False`; strip the `Optional` with [get_annotation_without_optional](#get_annotation_without_optional) first.
50
+
57
51
  ### get_annotation_origin
58
52
 
59
53
  Returns the base (origin) type of a generic annotation, unwrapping `NewType` and handling generic aliases recursively.
@@ -107,7 +101,7 @@ is_complex_sequence(dict) # False
107
101
  ### get_complex_sequence_element_annotation
108
102
 
109
103
  Returns the element type from a sequence annotation.
110
- Raises `ValueError` if the annotation doesn’t specify an element type.
104
+ Raises `ValueError` if the annotation is not a complex sequence or doesn’t specify an element type.
111
105
 
112
106
  ```python
113
107
  from typing import List, Set
@@ -120,7 +114,8 @@ get_complex_sequence_element_annotation(Set[str]) # <class 'str'>
120
114
 
121
115
  ### get_dict_items_annotation
122
116
 
123
- Returns the key and value types from a dictionary annotation.
117
+ Returns the key and value types from a dictionary annotation. Raises `TypeError` for an annotation that is not a
118
+ `dict`, `ValueError` for a bare `dict` without arguments.
124
119
 
125
120
  ```python
126
121
  from typing import Dict
@@ -167,7 +162,8 @@ Helper functions for inspecting and extending class-level behavior
167
162
  ### classproperty
168
163
 
169
164
  Works like `@property`, but for class attributes.
170
- Can be accessed as `ClassName.property_name` without creating an instance.
165
+ Can be accessed as `ClassName.property_name` without creating an instance. Read-only in the sense that there is
166
+ no setter: assigning to the attribute replaces the descriptor on the class.
171
167
 
172
168
  ```python
173
169
  from ddutils.class_helpers import classproperty
@@ -216,7 +212,8 @@ get_origin_class_of_method(B, 'method') # <class 'A'>
216
212
  ### get_generic_base_argument
217
213
 
218
214
  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.
215
+ subscripted, the `TypeVar` itself when the subclass is still generic. `position` picks the argument of a base
216
+ with several type parameters (default `0`).
220
217
 
221
218
  ```python
222
219
  from typing import Generic, TypeVar
@@ -240,9 +237,11 @@ get_generic_base_argument(Repository, Repository) # None
240
237
 
241
238
  ### require_class_attribute
242
239
 
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.
240
+ `require_class_attribute(cls, name, expected_type=None, *, allow_empty=False)` returns a class attribute that
241
+ subclasses are expected to declare, for `__init_subclass__` checks. A missing, `None` or empty value raises
242
+ `AttributeError`, a value that is not an instance of `expected_type` (a class or a tuple of classes, skipped when
243
+ `None`) raises `TypeError`; both name the attribute and the class, so a misconfigured subclass fails at definition
244
+ rather than on first use. `allow_empty=True` accepts `''`, `[]` or `{}`; numbers are never empty, `0` passes.
246
245
 
247
246
  ```python
248
247
  from typing import ClassVar
@@ -274,8 +273,10 @@ Tools for creating and modifying Python functions at runtime.
274
273
 
275
274
  ### create_new_function
276
275
 
277
- Creates a new function from an existing one, with an optional new name.
278
- Preserves default values and closures.
276
+ Creates a new function from an existing one, with an optional new name, by rebuilding its code object. It keeps
277
+ the code, globals and positional defaults (`__defaults__`); closure cells are copied as a snapshot of their
278
+ current values, so the copy does not follow later changes to the enclosed variables. Keyword-only defaults,
279
+ annotations, the docstring and `__qualname__` are not carried over.
279
280
 
280
281
  ```python
281
282
  from ddutils.function_helpers import create_new_function
@@ -373,44 +374,37 @@ Utilities for working with dates and times.
373
374
 
374
375
  ### utc_now
375
376
 
376
- Returns the current datetime in UTC timezone.
377
+ `utc_now() -> datetime`: the current time as an aware `datetime`, `datetime.now(tz=UTC)`.
377
378
 
378
379
  ## Safe Decorators
379
380
 
380
- Decorators that help functions fail safely and handle exceptions gracefully.
381
-
382
381
  ### safe_call
383
382
 
384
- Wraps a function to catch exceptions and return a default value instead of raising errors.
383
+ Retries a failing call and then falls back to a default or re-raises. The function runs up to `1 + retries`
384
+ times; an attempt fails when it raises one of `exceptions`. Without `default_result` the last error propagates,
385
+ so a `None` result always means the function returned `None`, never that an error was swallowed. Every failure
386
+ that is retried or replaced by the default is logged with its traceback unless `capture_exception=False`.
387
+ Coroutine functions are awaited inside the decorator, so the exceptions raised while awaiting are the ones handled.
385
388
 
386
389
  ```python
387
390
  import requests
391
+ from redis.exceptions import RedisError
388
392
  from ddutils.safe_decorators import safe_call
389
393
 
390
394
 
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
-
395
+ @safe_call(default_result=0)
396
+ def count_pending() -> int:
397
+ return requests.get('https://api.example.com/pending').json()['count'] # 0 on any error
396
398
 
397
- @safe_call(default_result=0, exceptions=(ValueError,))
398
- def convert_to_int(value):
399
- return int(value)
400
- ```
401
399
 
402
- ### retry_once_after_exception
400
+ @safe_call(retries=1, exceptions=(requests.ConnectionError,))
401
+ def fetch_report(url: str) -> requests.Response:
402
+ return requests.get(url) # one more try on a dropped connection, then the error
403
403
 
404
- Retries a function once if it raises an exception.
405
404
 
406
- ```python
407
- import requests
408
- from ddutils.safe_decorators import retry_once_after_exception
409
-
410
-
411
- @retry_once_after_exception
412
- def unstable_network_call():
413
- return requests.get('https://api.example.com/unstable')
405
+ @safe_call(default_result=None, exceptions=(RedisError,), capture_exception=False)
406
+ async def get_cached_profile(profile_id: int) -> Profile | None:
407
+ return await cache.get(profile_id) # None when Redis is unavailable
414
408
  ```
415
409
 
416
410
  ## Module and Object Management
@@ -419,7 +413,8 @@ Helpers for importing and accessing modules or objects at runtime.
419
413
 
420
414
  ### get_module
421
415
 
422
- Finds a nested module by path within a parent module.
416
+ Finds a nested module by path within a parent module. Raises `ValueError` when a step of the path is not an
417
+ attribute of the module reached so far.
423
418
 
424
419
  ```python
425
420
  import os
@@ -431,7 +426,8 @@ get_module(os, ['path']) # <module 'os.path'>
431
426
 
432
427
  ### get_object_by_path
433
428
 
434
- Imports and returns an object by its full dotted path (e.g. 'json.loads').
429
+ Imports and returns an object by its full dotted path (e.g. 'json.loads'). Returns `None` instead of raising when
430
+ the path is not a string, the module cannot be imported or the attribute does not exist.
435
431
 
436
432
  ```python
437
433
  from ddutils.object_getter import get_object_by_path
@@ -446,12 +442,13 @@ A registry that keeps one object instance per scope and manages its lifetime.
446
442
 
447
443
  ### ScopedRegistry
448
444
 
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`.
445
+ `ScopedRegistry(create_func, scope_func, destructor_method_name=None)` keeps one object per scope. `scope_func`
446
+ decides what the current scope is and returns its key; `None` means "no current scope" and makes every method
447
+ raise `RuntimeError`, as does a key that is not hashable. `asyncio.current_task` as the key needs a running loop.
451
448
 
452
449
  `scope()` is the entry point into a scope: it creates the object on enter and removes it on exit, calling
453
450
  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.
451
+ Concurrent first accesses with the same key call `create_func` only once; `create_func` may be sync or async.
455
452
 
456
453
  ```python
457
454
  import asyncio
@@ -479,34 +476,48 @@ Lower-level methods are available when a context manager does not fit:
479
476
  - `set(**kwargs)` returns the existing object or creates it. Whoever calls it takes over the cleanup that
480
477
  `scope()` does on exit and must call `clear()` when the object is no longer needed, if it ever is: a
481
478
  per-process client may live until the process ends;
482
- - `clear()` removes the object of the current scope and calls the destructor.
479
+ - `clear()` removes the object of the current scope and calls the destructor. Without a current scope it raises
480
+ like every other method, so call it where the scope exists: anywhere for `os.getpid`, inside the task for
481
+ `asyncio.current_task`, inside the block for a token scope.
483
482
 
484
- #### Scopes kept in a ContextVar
483
+ The `kwargs` of `scope()` and `set()` go to `create_func` only when the object is created; a call that joins an
484
+ existing object ignores them. `destructor_method_name` names a sync or async method of the object; `clear()`
485
+ removes the object from the registry first and then calls it once, and an exception from it propagates.
486
+ `registry` is the plain dict behind it, keyed by scope. One `asyncio.Lock` guards creation for all keys of a
487
+ registry, so a slow `create_func` in one scope delays first accesses in the others.
485
488
 
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.
489
+ #### process_loop_scope
490
+
491
+ A ready-made key for clients that are pools bound to their event loop (`redis.asyncio`, `aiokafka`,
492
+ `aerospike_native`): `(os.getpid(), asyncio.get_running_loop())`. A second loop in the same process, a script
493
+ calling `asyncio.run` twice or a test suite, gets its own client instead of an "attached to a different loop"
494
+ error, and the pid guards a forked child, whose inherited sockets must not be reused. Raises `RuntimeError`
495
+ outside of a running loop.
491
496
 
492
497
  ```python
493
- from contextvars import ContextVar
498
+ from ddutils.scoped_registry import ScopedRegistry, process_loop_scope
494
499
 
495
- execution_key: ContextVar[str | None] = ContextVar('execution_key', default=None)
500
+ redis_registry = ScopedRegistry(create_func=make_redis_client, scope_func=process_loop_scope, destructor_method_name='aclose')
501
+ ```
496
502
 
503
+ #### execution_scope
497
504
 
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
505
+ A `scope_func` that declares a `token` parameter receives a freshly generated token when `scope()` is entered
506
+ or `set()` is called, and `None` on every other access (`get`, `clear`, a nested `scope()`); a scope started by
507
+ `set()` must be ended by `clear()`. This is for a scope of one execution (an HTTP request, an actor run) rather
508
+ than one task: the function stores the token in a `ContextVar`, so coroutines spawned inside the block
509
+ (`gather`, `TaskGroup`, `create_task`) inherit it and share the object with the parent, while outside of
510
+ `scope()` there is no key and every method raises. `execution_scope(name)` is that function, with its own
511
+ `ContextVar` named `name`, so every registry gets a scope of its own:
512
+
513
+ ```python
514
+ from ddutils.scoped_registry import ScopedRegistry, execution_scope
504
515
 
505
516
 
506
517
  async def create_log_properties(**kwargs): ...
507
518
 
508
519
 
509
- log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope)
520
+ log_registry = ScopedRegistry(create_func=create_log_properties, scope_func=execution_scope('log_properties'))
510
521
 
511
522
 
512
523
  async def middleware(headers):
@@ -536,6 +547,11 @@ per task. The connections module adds two things on top:
536
547
  Databases with transactions pass their own `connection_manager_class`: a unit of work that begins, commits
537
548
  or rolls back and closes the session on exit. It depends on the driver, so it lives in the project.
538
549
 
550
+ The factory raises `ValueError` when `default` is not among the registries and `KeyError` for an unknown alias.
551
+ `ConnectionManager` enters with `registry.set()` and no arguments, so the `create_func` of its registries takes
552
+ none (use `functools.partial`). `close()` calls `clear()` on every registry, which needs a current scope: for
553
+ `process_loop_scope` that is inside the loop the clients were opened in, for example FastAPI's lifespan.
554
+
539
555
  ```python
540
556
  import os
541
557
  from enum import Enum
@@ -571,19 +587,46 @@ async with atomic(alias=PostgresDB.REPLICA) as session:
571
587
  await clickhouse.close()
572
588
  ```
573
589
 
590
+ ### connection_proxy
591
+
592
+ Some libraries want a connection object at construction and keep it for the life of the process: a rate limiter's
593
+ bucket, a lock implementation. `connection_proxy(factory, *, alias=None)` returns a `ConnectionProxy` typed as the
594
+ connection it stands in for; every method call borrows the connection from the factory for that one call and keeps
595
+ nothing of it, the way a ddsql adapter or a ddredis lock does by hand. A sync method is called inside the borrow as
596
+ well and its result returned as is.
597
+
598
+ ```python
599
+ from ddutils.connections import connection_proxy
600
+
601
+ bucket = await RedisBucket.init(rates, redis=connection_proxy(redis_client_factory), bucket_key='api')
602
+ ```
603
+
604
+ Only method calls are proxied: attributes and properties of the connection cannot be reached, since attribute
605
+ access cannot borrow. A sync method whose result stays bound to the connection (a pipeline) is safe only with a
606
+ manager that releases nothing on exit, such as `ConnectionManager`.
607
+
574
608
  ## Feature Flags
575
609
 
576
610
  `ddutils.feature_flags` is the storage-agnostic part of feature flags: `FeatureFlagRecord` (on or off, the proportion
577
611
  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.
612
+ through a storage with a cache. The storages live with their clients: `ddredis.feature_flags.RedisFeatureFlagStorage`,
613
+ `ddaerospike.feature_flags.AerospikeFeatureFlagStorage`.
614
+
615
+ `FeatureFlagRecord(enabled=False, proportion=1.0, payload={})` is what a storage holds for one flag; a flag that
616
+ does not exist reads as these defaults. The record validates itself on construction: `enabled` takes a bool or
617
+ what a storage may hold for one (`1`, `'true'`, `'yes'`, `'on'`, `'t'`, `'y'` and their negations), `proportion`
618
+ a number in 0..1, `payload` a mapping, which is copied. `from_dict` builds a record from what a storage read and
619
+ rejects unknown keys; `to_dict` is the inverse.
620
+
621
+ Readers see booleans and payloads, not records. `is_enabled(name, idempotent_key=None)` is the flag's switch and
622
+ its proportion in one answer: off for everyone when the flag is off, on for the `proportion` of the readers when
623
+ it is on. The proportion applies whenever the flag is on, so a gradual rollout is written with an explicit
624
+ `proportion` and a kill-switch keeps the default. With an `idempotent_key` (anything with a `__str__`: a user id,
625
+ an account id) the split is repeatable, the same key always lands on the same side: the bucket is
626
+ `blake2b(f'{name}:{key}')` scaled to 0..1 and compared with the proportion, so the same key may be on one side for one
627
+ flag and on the other for another. Without a key the split is random per call. `get_payload(name)` is the payload
628
+ as stored, `{}` for a missing flag; its shape is the application's, parse it there and do not mutate it, it is
629
+ the cached object.
587
630
 
588
631
  ```python
589
632
  from ddredis.feature_flags import RedisFeatureFlagStorage
@@ -591,7 +634,7 @@ from ddutils.feature_flags import FeatureFlags
591
634
 
592
635
  feature_flags = FeatureFlags(RedisFeatureFlagStorage(redis_client_factory))
593
636
 
594
- # a kill-switch: proportion 1.0, on or off for everyone
637
+ # a kill-switch: the default proportion, on or off for everyone
595
638
  if await feature_flags.is_enabled('new_checkout'):
596
639
  ...
597
640
 
@@ -604,11 +647,18 @@ if await feature_flags.is_enabled('email_provider_block'):
604
647
  rules = EmailProviderBlockRules.model_validate(await feature_flags.get_payload('email_provider_block'))
605
648
  ```
606
649
 
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.
650
+ `FeatureFlags(storage, base_ttl=BASE_TTL)` caches every flag it reads for `base_ttl` (15) plus 0 to `JITTER` (5)
651
+ seconds, so the readers of a process do not re-read at once. The cache belongs to the instance: keep one per
652
+ process, and expect a `put` to take up to a TTL to be seen, also from the process that wrote it. While the
653
+ storage fails, the last known record (or the defaults) is served and logged, and the re-read is retried with a
654
+ backoff from `ERROR_TTL` (1 second) doubling on every failure up to `base_ttl`.
655
+
656
+ A storage is a `FeatureFlagStorage` with `get(name) -> FeatureFlagRecord | None`, `get_map() -> dict[str, FeatureFlagRecord]`,
657
+ `put(name, record) -> None` (create or overwrite; there is no create-only) and `delete(name) -> bool`;
658
+ `rename(old_name, new_name, record)` defaults to put-then-delete and is overridden where the storage can do it
659
+ atomically. A storage builds records with `from_dict` and, when what it read is not a valid record, logs it and
660
+ reads it as the defaults. Only a failure of the storage itself raises, as `FeatureFlagStorageError` with the cause
661
+ chained.
612
662
 
613
663
  ## Context Helpers
614
664
 
@@ -631,8 +681,16 @@ AST-based introspection for extracting exceptions from function source code.
631
681
 
632
682
  ### extract_function_exceptions
633
683
 
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.
684
+ Parses a function’s source code to find all `raise` statements and identify the exception types they use.
685
+ Returns an iterator of `ExceptionInfo` objects describing each raised exception: `exception_class`, the
686
+ positional `args` and keyword `kwargs` of the `raise` as written, with any non-literal argument replaced by
687
+ `UNDEFINED_VALUE`. `get_kwargs()` maps them onto the parameters of the exception's `__init__`, filling in
688
+ defaults and class attributes; `get_exception_instance(dry_run=True)` builds the exception from them, with
689
+ `'<name>'` for undefined values, and returns `None` instead of raising when `dry_run`.
690
+
691
+ The function needs its source (`inspect.getsource`), so it does not work on builtins or code without a file.
692
+ A bare `raise` or `raise err` of a caught variable is skipped, an exception class that cannot be resolved by name
693
+ in the function's module or `builtins` is skipped too; `raise self.Error()` is not supported and raises `ValueError`.
636
694
 
637
695
  ## Value Helpers
638
696
 
@@ -1,5 +1,6 @@
1
- from collections.abc import Callable, Hashable, Mapping
2
- from typing import Any, Generic, TypeVar
1
+ import inspect
2
+ from collections.abc import Awaitable, Callable, Hashable, Mapping
3
+ from typing import Any, Generic, TypeVar, cast
3
4
 
4
5
  from ddutils.scoped_registry import ScopedRegistry
5
6
 
@@ -78,4 +79,44 @@ class ConnectionManagerFactory(Generic[ConnectionAliasT, ConnectionT, Connection
78
79
  await registry.clear()
79
80
 
80
81
 
81
- __all__ = ('ConnectionManager', 'ConnectionManagerFactory')
82
+ class ConnectionProxy(Generic[ConnectionT]):
83
+ """
84
+ Stands in for a connection in front of code that wants to hold one, typically a third-party library that takes a
85
+ client at construction and keeps it for the life of the process (a rate limiter's bucket, a lock implementation).
86
+ Every method call borrows the connection from the factory for that one call and keeps nothing of it, so the
87
+ factory's manager may hand out and release the connection however it sees fit, like `RedisLock` of ddredis does
88
+ by hand. A sync method is called inside the borrow as well and its result returned as is.
89
+
90
+ Only method calls are proxied. An attribute or property of the connection cannot be reached: attribute access is
91
+ synchronous and cannot borrow the connection. A sync method whose result stays bound to the connection (a
92
+ pipeline) is safe only with a manager that releases nothing on exit, such as `ConnectionManager`.
93
+ """
94
+
95
+ def __init__(self, factory: ConnectionManagerFactory[Any, ConnectionT, Any], *, alias: Hashable | None = None) -> None:
96
+ self._factory = factory
97
+ self._alias = alias
98
+
99
+ def __getattr__(self, name: str) -> Callable[..., Awaitable[Any]]:
100
+ if name.startswith('_'): # private and dunder lookups (copy, pickle, repr) are the proxy's own business
101
+ raise AttributeError(name)
102
+
103
+ async def call(*args: Any, **kwargs: Any) -> Any:
104
+ async with self._factory(alias=self._alias) as connection:
105
+ result = getattr(connection, name)(*args, **kwargs)
106
+ return await result if inspect.isawaitable(result) else result
107
+
108
+ call.__name__ = name
109
+ return call
110
+
111
+
112
+ def connection_proxy(factory: ConnectionManagerFactory[Any, ConnectionT, Any], *, alias: Hashable | None = None) -> ConnectionT:
113
+ """
114
+ A `ConnectionProxy` typed as the connection it stands in for, so it can be passed where the connection's type is
115
+ expected without a cast at the call site:
116
+
117
+ bucket = await RedisBucket.init(rates, redis=connection_proxy(redis_client_factory), bucket_key='api')
118
+ """
119
+ return cast('ConnectionT', ConnectionProxy(factory, alias=alias))
120
+
121
+
122
+ __all__ = ('ConnectionManager', 'ConnectionManagerFactory', 'ConnectionProxy', 'connection_proxy')
@@ -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
- description = "Domain Driven Utils Library"
4
- version = "0.3.3"
3
+ description = "Shared utilities of the dd libraries: annotation and class helpers, convertors, scoped registries, connection factories and feature flags"
4
+ version = "0.4.1"
5
5
  license = "MIT"
6
6
  license-files = ["LICENSE"]
7
7
  readme = "README.md"
@@ -9,6 +9,23 @@ requires-python = ">=3.11,<3.15"
9
9
  keywords = [
10
10
  "python",
11
11
  "ddutils",
12
+ "utils",
13
+ "helpers",
14
+ "type hints",
15
+ "type annotations",
16
+ "introspection",
17
+ "generics",
18
+ "scoped registry",
19
+ "context scope",
20
+ "connection manager",
21
+ "connection factory",
22
+ "feature flags",
23
+ "feature toggle",
24
+ "retry",
25
+ "safe call",
26
+ "decorators",
27
+ "convertors",
28
+ "asyncio",
12
29
  ]
13
30
  classifiers = [
14
31
  "Programming Language :: Python :: 3",
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "ddutils"
3
- description = "Domain Driven Utils Library"
4
- version = "0.3.3"
3
+ description = "Shared utilities of the dd libraries: annotation and class helpers, convertors, scoped registries, connection factories and feature flags"
4
+ version = "0.4.1"
5
5
  authors = [{ name = "davyddd" }]
6
6
  license = "MIT"
7
7
  license-files = ["LICENSE"]
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.11,<3.15"
10
- keywords = ["python", "ddutils"]
10
+ keywords = ["python", "ddutils", "utils", "helpers", "type hints", "type annotations", "introspection", "generics", "scoped registry", "context scope", "connection manager", "connection factory", "feature flags", "feature toggle", "retry", "safe call", "decorators", "convertors", "asyncio"]
11
11
  # uv_build does not derive these from requires-python (poetry did); PyPI and the pyversions badge read them
12
12
  classifiers = [
13
13
  "Programming Language :: Python :: 3",
@@ -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