| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
from types import MappingProxyType |
| 5 |
from typing import ( |
| 6 |
TYPE_CHECKING, |
| 7 |
Any, |
| 8 |
Callable, |
| 9 |
ClassVar, |
| 10 |
Generic, |
| 11 |
Literal, |
| 12 |
NamedTuple, |
| 13 |
TypeVar, |
| 14 |
overload, |
| 15 |
) |
| 16 |
|
| 17 |
from ._expressions import Name |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
import builtins |
| 21 |
from collections.abc import MutableMapping |
| 22 |
|
| 23 |
T = TypeVar("T") |
| 24 |
A = TypeVar("A") |
| 25 |
|
| 26 |
|
| 27 |
class __missing: |
| 28 |
"""Sentinel... done this way for the purpose of typing.""" |
| 29 |
|
| 30 |
def __repr__(self) -> str: |
| 31 |
return "MISSING" |
| 32 |
|
| 33 |
|
| 34 |
MISSING = __missing() |
| 35 |
|
| 36 |
|
| 37 |
class ContextKeyInfo(NamedTuple): |
| 38 |
"""Just a recordkeeping tuple. |
| 39 |
|
| 40 |
Retrieve all declared ContextKeys with ContextKeyInfo.info(). |
| 41 |
""" |
| 42 |
|
| 43 |
key: str |
| 44 |
type: type | None |
| 45 |
description: str | None |
| 46 |
namespace: builtins.type[ContextNamespace] | None |
| 47 |
|
| 48 |
|
| 49 |
class ContextKey(Name, Generic[A, T]): |
| 50 |
"""Context key name, default, description, and getter. |
| 51 |
|
| 52 |
This is intended to be used as class attribute in a `ContextNamespace`. |
| 53 |
This is a subclass of `Name`, and is therefore usable in an `Expression`. |
| 54 |
(see examples.) |
| 55 |
|
| 56 |
Parameters |
| 57 |
---------- |
| 58 |
default_value : Any, optional |
| 59 |
The default value for this key, by default MISSING |
| 60 |
description : str, optional |
| 61 |
Description of this key. Useful for documentation, by default None |
| 62 |
getter : callable, optional |
| 63 |
Callable that receives an object and retrieves the current value for |
| 64 |
this key, by default None. |
| 65 |
For example, if this ContextKey represented the length of some list, |
| 66 |
(like the layerlist) it might look like |
| 67 |
`length = ContextKey(0, 'length of the list', lambda x: len(x))` |
| 68 |
id : str, optional |
| 69 |
Explicitly provide the `Name` string used when evaluating a context, |
| 70 |
by default the key will be taken as the attribute name to which this |
| 71 |
object is assigned as a class attribute: |
| 72 |
|
| 73 |
Examples |
| 74 |
-------- |
| 75 |
>>> class MyNames(ContextNamespace): |
| 76 |
... some_key = ContextKey(0, "some description", lambda x: sum(x)) |
| 77 |
|
| 78 |
>>> expr = MyNames.some_key > 5 # create an expression using this key |
| 79 |
|
| 80 |
these expressions can be later evaluated with some concrete context. |
| 81 |
|
| 82 |
>>> expr.eval({"some_key": 3}) # False |
| 83 |
>>> expr.eval({"some_key": 6}) # True |
| 84 |
""" |
| 85 |
|
| 86 |
# This will catalog all ContextKeys that get instantiated, which provides |
| 87 |
# an easy way to organize documentation. |
| 88 |
# ContextKey.info() returns a list with info for all ContextKeys |
| 89 |
_info: ClassVar[list[ContextKeyInfo]] = [] |
| 90 |
MISSING = MISSING |
| 91 |
|
| 92 |
def __init__( |
| 93 |
self, |
| 94 |
default_value: T | __missing = MISSING, |
| 95 |
description: str | None = None, |
| 96 |
getter: Callable[[A], T] | None = None, |
| 97 |
*, |
| 98 |
id: str = "", # optional because of __set_name__ |
| 99 |
) -> None: |
| 100 |
bound = type(default_value) if default_value is not MISSING else None |
| 101 |
super().__init__(id or "", bound=bound) |
| 102 |
self._default_value = default_value |
| 103 |
self._getter = getter |
| 104 |
self._description = description |
| 105 |
self._owner: type[ContextNamespace] | None = None |
| 106 |
self._type = ( |
| 107 |
type(default_value) if default_value not in (None, MISSING) else None |
| 108 |
) |
| 109 |
if id: |
| 110 |
self._store() |
| 111 |
|
| 112 |
def __str__(self) -> str: |
| 113 |
return self.id |
| 114 |
|
| 115 |
@classmethod |
| 116 |
def info(cls) -> list[ContextKeyInfo]: |
| 117 |
"""Return list of all stored context keys.""" |
| 118 |
return list(cls._info) |
| 119 |
|
| 120 |
def _store(self) -> None: |
| 121 |
self._info.append( |
| 122 |
ContextKeyInfo(self.id, self._type, self._description, self._owner) |
| 123 |
) |
| 124 |
|
| 125 |
def __set_name__(self, owner: type[ContextNamespace[A]], name: str) -> None: |
| 126 |
"""Set the name for this key. |
| 127 |
|
| 128 |
(this happens when you instantiate this class as a class attribute). |
| 129 |
""" |
| 130 |
if self.id: |
| 131 |
raise RuntimeError( |
| 132 |
f"Cannot change id of ContextKey (already {self.id!r})", |
| 133 |
) |
| 134 |
self._owner = owner |
| 135 |
self.id = name |
| 136 |
# recompile the code with the new name |
| 137 |
self._recompile() |
| 138 |
self._store() |
| 139 |
|
| 140 |
@overload |
| 141 |
def __get__(self, obj: Literal[None], objtype: type) -> ContextKey[A, T]: |
| 142 |
# When we __get__ from the class, we return ourself |
| 143 |
... |
| 144 |
|
| 145 |
@overload |
| 146 |
def __get__(self, obj: ContextNamespace[A], objtype: type) -> T: |
| 147 |
# When we got from the object, we return the current value |
| 148 |
... |
| 149 |
|
| 150 |
def __get__( |
| 151 |
self, obj: ContextNamespace[A] | None, objtype: type |
| 152 |
) -> T | ContextKey[A, T] | None: |
| 153 |
"""Get current value of the key in the associated context.""" |
| 154 |
return self if obj is None else obj._context.get(self.id, MISSING) |
| 155 |
|
| 156 |
def __set__(self, obj: ContextNamespace[A], value: T) -> None: |
| 157 |
"""Set current value of the key in the associated context.""" |
| 158 |
obj._context[self.id] = value |
| 159 |
|
| 160 |
def __delete__(self, obj: ContextNamespace[A]) -> None: |
| 161 |
"""Delete key from the associated context.""" |
| 162 |
del obj._context[self.id] |
| 163 |
|
| 164 |
|
| 165 |
class ContextNamespaceMeta(type): |
| 166 |
"""Metaclass that finds all ContextNamespace members.""" |
| 167 |
|
| 168 |
_members_map_: dict[str, ContextKey] |
| 169 |
|
| 170 |
def __new__(cls, clsname: str, bases: tuple, attrs: dict) -> ContextNamespaceMeta: |
| 171 |
"""Create a new ContextNamespace class.""" |
| 172 |
new_cls = super().__new__(cls, clsname, bases, attrs) |
| 173 |
new_cls._members_map_ = { |
| 174 |
k: v for k, v in attrs.items() if isinstance(v, ContextKey) |
| 175 |
} |
| 176 |
return new_cls |
| 177 |
|
| 178 |
@property |
| 179 |
def __members__(self) -> MappingProxyType[str, ContextKey]: |
| 180 |
return MappingProxyType(self._members_map_) |
| 181 |
|
| 182 |
def __dir__(self) -> list[str]: # pragma: no cover |
| 183 |
return [ |
| 184 |
"__class__", |
| 185 |
"__doc__", |
| 186 |
"__members__", |
| 187 |
"__module__", |
| 188 |
*list(self._members_map_), |
| 189 |
] |
| 190 |
|
| 191 |
|
| 192 |
class ContextNamespace(Generic[A], metaclass=ContextNamespaceMeta): |
| 193 |
"""A collection of related keys in a context. |
| 194 |
|
| 195 |
meant to be subclassed, with `ContextKeys` as class attributes. |
| 196 |
""" |
| 197 |
|
| 198 |
def __init__(self, context: MutableMapping) -> None: |
| 199 |
self._context = context |
| 200 |
|
| 201 |
# on instantiation we create an index of defaults and value-getters |
| 202 |
# to speed up retrieval later |
| 203 |
self._defaults: dict[str, Any] = {} # default values per key |
| 204 |
self._getters: dict[str, Callable[[A], Any]] = {} # value getters |
| 205 |
for name, ctxkey in type(self).__members__.items(): |
| 206 |
self._defaults[name] = ctxkey._default_value |
| 207 |
if ctxkey._default_value is not MISSING: |
| 208 |
context[ctxkey.id] = ctxkey._default_value |
| 209 |
if callable(ctxkey._getter): |
| 210 |
self._getters[name] = ctxkey._getter |
| 211 |
|
| 212 |
def reset(self, key: str) -> None: |
| 213 |
"""Reset keys to its default.""" |
| 214 |
val = self._defaults[key] |
| 215 |
if val is MISSING: |
| 216 |
with contextlib.suppress(KeyError): |
| 217 |
delattr(self, key) |
| 218 |
else: |
| 219 |
setattr(self, key, self._defaults[key]) |
| 220 |
|
| 221 |
def reset_all(self) -> None: |
| 222 |
"""Reset all keys to their defaults.""" |
| 223 |
for key in self._defaults: |
| 224 |
self.reset(key) |
| 225 |
|
| 226 |
def dict(self) -> dict: |
| 227 |
"""Return all keys in this namespace.""" |
| 228 |
return {k: getattr(self, k) for k in type(self).__members__} |
| 229 |
|
| 230 |
def __repr__(self) -> str: |
| 231 |
import pprint |
| 232 |
|
| 233 |
return pprint.pformat(self.dict()) |