Debian Codegraph @

Lib/test/support/interpreters/_crossinterp.py

raw
1 """Common code between queues and channels."""
2
3
4 class ItemInterpreterDestroyed(Exception):
5 """Raised when trying to get an item whose interpreter was destroyed."""
6
7
8 class classonly:
9 """A non-data descriptor that makes a value only visible on the class.
10
11 This is like the "classmethod" builtin, but does not show up on
12 instances of the class. It may be used as a decorator.
13 """
14
15 def __init__(self, value):
16 self.value = value
17 self.getter = classmethod(value).__get__
18 self.name = None
19
20 def __set_name__(self, cls, name):
21 if self.name is not None:
22 raise TypeError('already used')
23 self.name = name
24
25 def __get__(self, obj, cls):
26 if obj is not None:
27 raise AttributeError(self.name)
28 # called on the class
29 return self.getter(None, cls)
30
31
32 class UnboundItem:
33 """Represents a cross-interpreter item no longer bound to an interpreter.
34
35 An item is unbound when the interpreter that added it to the
36 cross-interpreter container is destroyed.
37 """
38
39 __slots__ = ()
40
41 @classonly
42 def singleton(cls, kind, module, name='UNBOUND'):
43 doc = cls.__doc__.replace('cross-interpreter container', kind)
44 doc = doc.replace('cross-interpreter', kind)
45 subclass = type(
46 f'Unbound{kind.capitalize()}Item',
47 (cls,),
48 dict(
49 _MODULE=module,
50 _NAME=name,
51 __doc__=doc,
52 ),
53 )
54 return object.__new__(subclass)
55
56 _MODULE = __name__
57 _NAME = 'UNBOUND'
58
59 def __new__(cls):
60 raise Exception(f'use {cls._MODULE}.{cls._NAME}')
61
62 def __repr__(self):
63 return f'{self._MODULE}.{self._NAME}'
64 # return f'interpreters.queues.UNBOUND'
65
66
67 UNBOUND = object.__new__(UnboundItem)
68 UNBOUND_ERROR = object()
69 UNBOUND_REMOVE = object()
70
71 _UNBOUND_CONSTANT_TO_FLAG = {
72 UNBOUND_REMOVE: 1,
73 UNBOUND_ERROR: 2,
74 UNBOUND: 3,
75 }
76 _UNBOUND_FLAG_TO_CONSTANT = {v: k
77 for k, v in _UNBOUND_CONSTANT_TO_FLAG.items()}
78
79
80 def serialize_unbound(unbound):
81 op = unbound
82 try:
83 flag = _UNBOUND_CONSTANT_TO_FLAG[op]
84 except KeyError:
85 raise NotImplementedError(f'unsupported unbound replacement op {op!r}')
86 return flag,
87
88
89 def resolve_unbound(flag, exctype_destroyed):
90 try:
91 op = _UNBOUND_FLAG_TO_CONSTANT[flag]
92 except KeyError:
93 raise NotImplementedError(f'unsupported unbound replacement op {flag!r}')
94 if op is UNBOUND_REMOVE:
95 # "remove" not possible here
96 raise NotImplementedError
97 elif op is UNBOUND_ERROR:
98 raise exctype_destroyed("item's original interpreter destroyed")
99 elif op is UNBOUND:
100 return UNBOUND
101 else:
102 raise NotImplementedError(repr(op))