| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import sys |
| 5 |
from collections import ChainMap |
| 6 |
from contextlib import contextmanager |
| 7 |
from typing import TYPE_CHECKING, Any, Callable |
| 8 |
from weakref import finalize |
| 9 |
|
| 10 |
from psygnal import Signal |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from collections.abc import Iterator, MutableMapping |
| 14 |
from types import FrameType |
| 15 |
from typing import TypedDict |
| 16 |
|
| 17 |
class AppModelContextDict(TypedDict): |
| 18 |
"""Global context keys offered by app-model.""" |
| 19 |
|
| 20 |
is_linux: bool |
| 21 |
is_mac: bool |
| 22 |
is_windows: bool |
| 23 |
|
| 24 |
|
| 25 |
_null = object() |
| 26 |
|
| 27 |
|
| 28 |
class Context(ChainMap): |
| 29 |
"""Evented Mapping of keys to values.""" |
| 30 |
|
| 31 |
changed = Signal(set) # Set[str] |
| 32 |
|
| 33 |
def __init__(self, *maps: MutableMapping) -> None: |
| 34 |
super().__init__(*maps) |
| 35 |
for m in maps: |
| 36 |
if isinstance(m, Context): |
| 37 |
m.changed.connect(self.changed) |
| 38 |
|
| 39 |
@contextmanager |
| 40 |
def buffered_changes(self) -> Iterator[None]: |
| 41 |
"""Context in which to accumulated changes before emitting.""" |
| 42 |
with self.changed.paused(lambda a, b: (a[0].union(b[0]),)): |
| 43 |
yield |
| 44 |
|
| 45 |
def __setitem__(self, k: str, v: Any) -> None: |
| 46 |
emit = self.get(k, _null) is not v |
| 47 |
super().__setitem__(k, v) |
| 48 |
if emit: |
| 49 |
self.changed.emit({k}) |
| 50 |
|
| 51 |
def __delitem__(self, k: str) -> None: |
| 52 |
emit = k in self |
| 53 |
super().__delitem__(k) |
| 54 |
if emit: |
| 55 |
self.changed.emit({k}) |
| 56 |
|
| 57 |
def new_child(self, m: MutableMapping | None = None) -> Context: |
| 58 |
"""Create a new child context from this one.""" |
| 59 |
new = super().new_child(m=m) |
| 60 |
self.changed.connect(new.changed) |
| 61 |
return new |
| 62 |
|
| 63 |
def __hash__(self) -> int: |
| 64 |
return id(self) |
| 65 |
|
| 66 |
|
| 67 |
# note: it seems like WeakKeyDictionary would be a nice match here, but |
| 68 |
# it appears that the object somehow isn't initialized "enough" to register |
| 69 |
# as the same object in the WeakKeyDictionary later when queried with |
| 70 |
# `obj in _OBJ_TO_CONTEXT` ... so instead we use id(obj) |
| 71 |
# _OBJ_TO_CONTEXT: WeakKeyDictionary[object, Context] = WeakKeyDictionary() |
| 72 |
_OBJ_TO_CONTEXT: dict[int, Context] = {} |
| 73 |
_ROOT_CONTEXT: Context | None = None |
| 74 |
|
| 75 |
|
| 76 |
def _pydantic_abort(frame: FrameType) -> bool: |
| 77 |
# type is being declared and pydantic is checking defaults |
| 78 |
# this context will never be used. |
| 79 |
return frame.f_code.co_name in ("__new__", "_set_default_and_type") |
| 80 |
|
| 81 |
|
| 82 |
def create_context( |
| 83 |
obj: object, |
| 84 |
max_depth: int = 20, |
| 85 |
start: int = 2, |
| 86 |
root: Context | None = None, |
| 87 |
root_class: type[Context] = Context, |
| 88 |
frame_predicate: Callable[[FrameType], bool] = _pydantic_abort, |
| 89 |
) -> Context: |
| 90 |
"""Create context for any object. |
| 91 |
|
| 92 |
Parameters |
| 93 |
---------- |
| 94 |
obj : object |
| 95 |
Any object |
| 96 |
max_depth : int, optional |
| 97 |
Max frame depth to search for another object (that already has a context) off |
| 98 |
of which to scope this new context. by default 20 |
| 99 |
start : int, optional |
| 100 |
first frame to use in search, by default 2 |
| 101 |
root : Optional[Context], optional |
| 102 |
Root context to use, by default None |
| 103 |
root_class : type[Context], optional |
| 104 |
Root class to use when creating a global root context, by default Context |
| 105 |
The global context is used when root is None. |
| 106 |
frame_predicate : Callable[[FrameType], bool], optional |
| 107 |
Callback that can be used to abort context creation. Will be called on each |
| 108 |
frame in the stack, and if it returns True, the context will not be created. |
| 109 |
by default, uses pydantic-specific function to determine if a new pydantic |
| 110 |
BaseModel is being *declared*, (which means that the context will never be used) |
| 111 |
`lambda frame: frame.f_code.co_name in ("__new__", "_set_default_and_type")` |
| 112 |
|
| 113 |
Returns |
| 114 |
------- |
| 115 |
Optional[Context] |
| 116 |
Context for the object, or None if no context was found |
| 117 |
""" |
| 118 |
if root is None: |
| 119 |
global _ROOT_CONTEXT |
| 120 |
if _ROOT_CONTEXT is None: |
| 121 |
_ROOT_CONTEXT = root_class() |
| 122 |
root = _ROOT_CONTEXT |
| 123 |
else: |
| 124 |
assert isinstance(root, Context), "root must be an instance of Context" |
| 125 |
|
| 126 |
parent = root |
| 127 |
if hasattr(sys, "_getframe"): # CPython implementation detail |
| 128 |
frame: FrameType | None = sys._getframe(start) |
| 129 |
i = -1 |
| 130 |
# traverse call stack looking for another object that has a context |
| 131 |
# to scope this new context off of. |
| 132 |
while frame and (i := i + 1) < max_depth: |
| 133 |
if frame_predicate(frame): |
| 134 |
return root # pragma: no cover # FIXME: should this be allowed? |
| 135 |
|
| 136 |
# FIXME: this might be a bit napari "magic" |
| 137 |
# it also assumes someone uses "self" as the first argument |
| 138 |
if "self" in frame.f_locals: |
| 139 |
_ctx = _OBJ_TO_CONTEXT.get(id(frame.f_locals["self"])) |
| 140 |
if _ctx is not None: |
| 141 |
parent = _ctx |
| 142 |
break |
| 143 |
frame = frame.f_back |
| 144 |
|
| 145 |
new_context = parent.new_child() |
| 146 |
obj_id = id(obj) |
| 147 |
_OBJ_TO_CONTEXT[obj_id] = new_context |
| 148 |
# remove key from dict when object is deleted |
| 149 |
finalize(obj, lambda: _OBJ_TO_CONTEXT.pop(obj_id, None)) |
| 150 |
return new_context |
| 151 |
|
| 152 |
|
| 153 |
def get_context(obj: object) -> Context | None: |
| 154 |
"""Return context for any object, if found.""" |
| 155 |
return _OBJ_TO_CONTEXT.get(id(obj)) |
| 156 |
|
| 157 |
|
| 158 |
def app_model_context() -> AppModelContextDict: |
| 159 |
"""A set of useful global context keys to use.""" |
| 160 |
return { |
| 161 |
"is_linux": sys.platform.startswith("linux"), |
| 162 |
"is_mac": sys.platform == "darwin", |
| 163 |
"is_windows": os.name == "nt", |
| 164 |
} |