| 1 |
from __pypy__ import get_contextvar_context, set_contextvar_context |
| 2 |
from _immutables_map import Map |
| 3 |
from _pypy_generic_alias import GenericAlias |
| 4 |
try: |
| 5 |
from __pypy__ import hidden_applevel |
| 6 |
except ImportError: |
| 7 |
hidden_applevel = lambda f: f |
| 8 |
|
| 9 |
|
| 10 |
_NO_DEFAULT = object() |
| 11 |
|
| 12 |
|
| 13 |
class Unsubclassable(type): |
| 14 |
def __new__(cls, name, bases, dct): |
| 15 |
for base in bases: |
| 16 |
if isinstance(base, Unsubclassable): |
| 17 |
raise TypeError(f"type '{base.__name__}' is not an acceptable base type") |
| 18 |
return type.__new__(cls, name, bases, dict(dct)) |
| 19 |
|
| 20 |
|
| 21 |
def get_context(): |
| 22 |
context = get_contextvar_context() |
| 23 |
if context is None: |
| 24 |
context = Context() |
| 25 |
set_contextvar_context(context) |
| 26 |
return context |
| 27 |
|
| 28 |
|
| 29 |
class Context(metaclass=Unsubclassable): |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
def __init__(self): |
| 35 |
self._data = Map() |
| 36 |
self._is_entered = False |
| 37 |
|
| 38 |
@hidden_applevel |
| 39 |
def run(self, callable, *args, **kwargs): |
| 40 |
if self._is_entered: |
| 41 |
raise RuntimeError( |
| 42 |
f'cannot enter context: {self} is already entered') |
| 43 |
|
| 44 |
|
| 45 |
_prev_context = get_contextvar_context() |
| 46 |
try: |
| 47 |
self._is_entered = True |
| 48 |
set_contextvar_context(self) |
| 49 |
return callable(*args, **kwargs) |
| 50 |
finally: |
| 51 |
set_contextvar_context(_prev_context) |
| 52 |
self._is_entered = False |
| 53 |
|
| 54 |
def copy(self): |
| 55 |
new = Context() |
| 56 |
new._data = self._data |
| 57 |
return new |
| 58 |
|
| 59 |
|
| 60 |
def __getitem__(self, var): |
| 61 |
if not isinstance(var, ContextVar): |
| 62 |
raise TypeError("ContextVar key was expected") |
| 63 |
return self._data[var] |
| 64 |
|
| 65 |
|
| 66 |
def __contains__(self, var): |
| 67 |
if not isinstance(var, ContextVar): |
| 68 |
raise TypeError("ContextVar key was expected") |
| 69 |
return var in self._data |
| 70 |
|
| 71 |
|
| 72 |
def __len__(self): |
| 73 |
return len(self._data) |
| 74 |
|
| 75 |
|
| 76 |
def __iter__(self): |
| 77 |
return iter(self._data) |
| 78 |
|
| 79 |
def get(self, key, default=None): |
| 80 |
if not isinstance(key, ContextVar): |
| 81 |
raise TypeError("ContextVar key was expected") |
| 82 |
try: |
| 83 |
return self._data[key] |
| 84 |
except KeyError: |
| 85 |
return default |
| 86 |
|
| 87 |
def keys(self): |
| 88 |
from collections.abc import KeysView |
| 89 |
return KeysView(self) |
| 90 |
|
| 91 |
def values(self): |
| 92 |
from collections.abc import ValuesView |
| 93 |
return ValuesView(self) |
| 94 |
|
| 95 |
def items(self): |
| 96 |
from collections.abc import ItemsView |
| 97 |
return ItemsView(self) |
| 98 |
|
| 99 |
def __eq__(self, other): |
| 100 |
if not isinstance(other, Context): |
| 101 |
return NotImplemented |
| 102 |
return dict(self.items()) == dict(other.items()) |
| 103 |
|
| 104 |
|
| 105 |
def copy_context(): |
| 106 |
return get_context().copy() |
| 107 |
|
| 108 |
class ContextVar(metaclass=Unsubclassable): |
| 109 |
|
| 110 |
def __init__(self, name, *, default=_NO_DEFAULT): |
| 111 |
if not isinstance(name, str): |
| 112 |
raise TypeError("context variable name must be a str") |
| 113 |
self._name = name |
| 114 |
self._default = default |
| 115 |
|
| 116 |
@property |
| 117 |
def name(self): |
| 118 |
return self._name |
| 119 |
|
| 120 |
def get(self, default=_NO_DEFAULT): |
| 121 |
|
| 122 |
context = get_contextvar_context() |
| 123 |
if context is not None: |
| 124 |
try: |
| 125 |
return context[self] |
| 126 |
except KeyError: |
| 127 |
pass |
| 128 |
|
| 129 |
if default is not _NO_DEFAULT: |
| 130 |
return default |
| 131 |
|
| 132 |
if self._default is not _NO_DEFAULT: |
| 133 |
return self._default |
| 134 |
|
| 135 |
raise LookupError |
| 136 |
|
| 137 |
def set(self, value): |
| 138 |
context = get_context() |
| 139 |
|
| 140 |
data: Map = context._data |
| 141 |
try: |
| 142 |
old_value = data[self] |
| 143 |
except KeyError: |
| 144 |
old_value = Token.MISSING |
| 145 |
|
| 146 |
updated_data = data.set(self, value) |
| 147 |
context._data = updated_data |
| 148 |
return Token(context, self, old_value) |
| 149 |
|
| 150 |
def reset(self, token): |
| 151 |
if token._used: |
| 152 |
raise RuntimeError("Token has already been used once") |
| 153 |
|
| 154 |
if token._var is not self: |
| 155 |
raise ValueError( |
| 156 |
"Token was created by a different ContextVar") |
| 157 |
|
| 158 |
context = get_context() |
| 159 |
if token._context is not context: |
| 160 |
raise ValueError( |
| 161 |
"Token was created in a different Context") |
| 162 |
|
| 163 |
if token._old_value is Token.MISSING: |
| 164 |
context._data = context._data.delete(token._var) |
| 165 |
else: |
| 166 |
context._data = context._data.set(token._var, token._old_value) |
| 167 |
|
| 168 |
token._used = True |
| 169 |
|
| 170 |
def __class_getitem__(self, item): |
| 171 |
return GenericAlias(self, item) |
| 172 |
|
| 173 |
def __repr__(self): |
| 174 |
default = '' |
| 175 |
if self._default is not _NO_DEFAULT: |
| 176 |
default = f"default={self._default} " |
| 177 |
return f"<ContextVar name={self.name!r} {default}at 0x{id(self):x}>" |
| 178 |
|
| 179 |
|
| 180 |
class Token(metaclass=Unsubclassable): |
| 181 |
MISSING = object() |
| 182 |
|
| 183 |
def __init__(self, context, var, old_value): |
| 184 |
self._context = context |
| 185 |
self._var = var |
| 186 |
self._old_value = old_value |
| 187 |
self._used = False |
| 188 |
|
| 189 |
@property |
| 190 |
def var(self): |
| 191 |
return self._var |
| 192 |
|
| 193 |
@property |
| 194 |
def old_value(self): |
| 195 |
return self._old_value |
| 196 |
|
| 197 |
def __repr__(self): |
| 198 |
return f"<Token {'used ' if self._used else ''}var={self._var} at 0x{id(self):x}>" |
| 199 |
|
| 200 |
def __class_getitem__(self, item): |
| 201 |
return GenericAlias(self, item) |