(original) (raw)

On 17 October 2017 at 15:02, Nick Coghlan <ncoghlan@gmail.com> wrote:
On 17 October 2017 at 14:31, Guido van Rossum <guido@python.org> wrote:
No, that version just defers to magic in ContextVar.get/set, whereas what I'd like to see is that the latter are just implemented in terms of manipulating the mapping directly. The only operations for which speed matters would be \_\_getitem\_\_ and \_\_setitem\_\_; most other methods just defer to those. \_\_delitem\_\_ must also be a primitive, as must \_\_iter\_\_ and \_\_len\_\_ -- but those don't need to be as speedy (however \_\_delitem\_\_ must really work!).

To have the mapping API at the base of the design, we'd want to go back to using the ContextKey version of the API as the core primitive (to ensure we don't get name conflicts between different modules and packages), and then have ContextVar be a convenience wrapper that always accesses the currently active context:

class ContextKey:
...
class ExecutionContext:
...

class ContextVar:
def \_\_init\_\_(self, name):
self.\_key = ContextKey(name)

def get(self):
return get\_execution\_context()\[self.\_key\]
def set(self, value):
get\_execution\_context()\[self.\_key\] = value

def delete(self, value):
del get\_execution\_context()\[self.\_key\]

Tangent: if we do go this way, it actually maps pretty nicely to the idea of a "threading.ThreadVar" API that wraps threading.local():

class ThreadVar:
def \_\_init\_\_(self, name):
self.\_name = name
self.\_storage = threading.local()

def get(self):
return self.\_storage.value
def set(self, value):
self.\_storage.value = value

def delete(self):
del self.\_storage.value

(Note: real implementations of either idea would need to pay more attention to producing clear exception messages and instance representations)

Cheers,
Nick.

--
Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia