Skip to content

Commit

Permalink
Add some docs, add self-registering
Browse files Browse the repository at this point in the history
  • Loading branch information
devkral committed Nov 22, 2024
1 parent d4fc629 commit 4f5cb5f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/cages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Cages

Cages are a way to manage global states in an non-global maner.


## Usage

There are two methods

1. registering via self registering (recommended)
2. registering manually

The first way is recommended because it can be detected if it would nest another Cage object.
In this case it would just skip the initialization and the old Cage is kept.

Advantage of this: multiple libraries can patch other libraries without fearing to overwrite another cage.
5 changes: 5 additions & 0 deletions monkay/cages.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,16 @@ def __init__(
# for e.g. locks
original_wrapper: AbstractContextManager = nullcontext(),
update_fn: Callable[[T, T], T] | None = None,
self_register: bool = True,
):
if name is None:
assert obj is not Undefined
name = obj.__name__ if isclass(obj) else type(obj).__name__
elif obj is Undefined:
obj = globals_dict[name]
assert obj is not Undefined
if self_register and issubclass(type(obj), Cage):
return
context_var_name = context_var_name.format(name=name)
self.monkay_context_var = globals_dict[context_var_name] = ContextVar[
tuple[int, T] | type[Undefined]
Expand All @@ -46,6 +49,8 @@ def __init__(
self.monkay_original_last_update = 0
self.monkay_original_last_update_lock = None if update_fn is None else Lock()
self.monkay_original_wrapper = original_wrapper
if self_register:
globals_dict[name] = self

def monkay_refresh_copy(
self, *, obj: T | type[Undefined] = Undefined, _monkay_dict: dict | None = None
Expand Down

0 comments on commit 4f5cb5f

Please sign in to comment.