MCPcopy Index your code
hub / github.com/python/cpython / _localimpl

Class _localimpl

Lib/_threading_local.py:24–65  ·  view source on GitHub ↗

A class managing thread-local dicts

Source from the content-addressed store, hash-verified

22# manifest.
23
24class _localimpl:
25 """A class managing thread-local dicts"""
26 __slots__ = 'key', 'dicts', 'localargs', 'locallock', '__weakref__'
27
28 def __init__(self):
29 # The key used in the Thread objects' attribute dicts.
30 # We keep it a string for speed but make it unlikely to clash with
31 # a "real" attribute.
32 self.key = '_threading_local._localimpl.' + str(id(self))
33 # { id(Thread) -> (ref(Thread), thread-local dict) }
34 self.dicts = {}
35
36 def get_dict(self):
37 """Return the dict for the current thread. Raises KeyError if none
38 defined."""
39 thread = current_thread()
40 return self.dicts[id(thread)][1]
41
42 def create_dict(self):
43 """Create a new dict for the current thread, and return it."""
44 localdict = {}
45 key = self.key
46 thread = current_thread()
47 idt = id(thread)
48 def local_deleted(_, key=key):
49 # When the localimpl is deleted, remove the thread attribute.
50 thread = wrthread()
51 if thread is not None:
52 del thread.__dict__[key]
53 def thread_deleted(_, idt=idt):
54 # When the thread is deleted, remove the local dict.
55 # Note that this is suboptimal if the thread object gets
56 # caught in a reference loop. We would like to be called
57 # as soon as the OS-level thread ends instead.
58 local = wrlocal()
59 if local is not None:
60 local.dicts.pop(idt)
61 wrlocal = ref(self, local_deleted)
62 wrthread = ref(thread, thread_deleted)
63 thread.__dict__[key] = wrlocal
64 self.dicts[idt] = wrthread, localdict
65 return localdict
66
67
68@contextmanager

Callers 1

__new__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…