A cross-interpreter queue.
| 95 | _known_queues = weakref.WeakValueDictionary() |
| 96 | |
| 97 | class Queue: |
| 98 | """A cross-interpreter queue.""" |
| 99 | |
| 100 | def __new__(cls, id, /): |
| 101 | # There is only one instance for any given ID. |
| 102 | if isinstance(id, int): |
| 103 | id = int(id) |
| 104 | else: |
| 105 | raise TypeError(f'id must be an int, got {id!r}') |
| 106 | try: |
| 107 | self = _known_queues[id] |
| 108 | except KeyError: |
| 109 | self = super().__new__(cls) |
| 110 | self._id = id |
| 111 | _known_queues[id] = self |
| 112 | _queues.bind(id) |
| 113 | return self |
| 114 | |
| 115 | def __del__(self): |
| 116 | try: |
| 117 | _queues.release(self._id) |
| 118 | except QueueNotFoundError: |
| 119 | pass |
| 120 | try: |
| 121 | del _known_queues[self._id] |
| 122 | except KeyError: |
| 123 | pass |
| 124 | |
| 125 | def __repr__(self): |
| 126 | return f'{type(self).__name__}({self.id})' |
| 127 | |
| 128 | def __hash__(self): |
| 129 | return hash(self._id) |
| 130 | |
| 131 | # for pickling: |
| 132 | def __reduce__(self): |
| 133 | return (type(self), (self._id,)) |
| 134 | |
| 135 | def _set_unbound(self, op, items=None): |
| 136 | assert not hasattr(self, '_unbound') |
| 137 | if items is None: |
| 138 | items = _resolve_unbound(op) |
| 139 | unbound = (op, items) |
| 140 | self._unbound = unbound |
| 141 | return unbound |
| 142 | |
| 143 | @property |
| 144 | def id(self): |
| 145 | return self._id |
| 146 | |
| 147 | @property |
| 148 | def unbounditems(self): |
| 149 | try: |
| 150 | _, items = self._unbound |
| 151 | except AttributeError: |
| 152 | op, _ = _queues.get_queue_defaults(self._id) |
| 153 | _, items = self._set_unbound(op) |
| 154 | return items |