Context manager catching threading.Thread exception using threading.excepthook. Attributes set when an exception is caught: * exc_type * exc_value * exc_traceback * thread See threading.excepthook() documentation for these attributes. These attributes are del
| 160 | |
| 161 | |
| 162 | class catch_threading_exception: |
| 163 | """ |
| 164 | Context manager catching threading.Thread exception using |
| 165 | threading.excepthook. |
| 166 | |
| 167 | Attributes set when an exception is caught: |
| 168 | |
| 169 | * exc_type |
| 170 | * exc_value |
| 171 | * exc_traceback |
| 172 | * thread |
| 173 | |
| 174 | See threading.excepthook() documentation for these attributes. |
| 175 | |
| 176 | These attributes are deleted at the context manager exit. |
| 177 | |
| 178 | Usage: |
| 179 | |
| 180 | with threading_helper.catch_threading_exception() as cm: |
| 181 | # code spawning a thread which raises an exception |
| 182 | ... |
| 183 | |
| 184 | # check the thread exception, use cm attributes: |
| 185 | # exc_type, exc_value, exc_traceback, thread |
| 186 | ... |
| 187 | |
| 188 | # exc_type, exc_value, exc_traceback, thread attributes of cm no longer |
| 189 | # exists at this point |
| 190 | # (to avoid reference cycles) |
| 191 | """ |
| 192 | |
| 193 | def __init__(self): |
| 194 | self.exc_type = None |
| 195 | self.exc_value = None |
| 196 | self.exc_traceback = None |
| 197 | self.thread = None |
| 198 | self._old_hook = None |
| 199 | |
| 200 | def _hook(self, args): |
| 201 | self.exc_type = args.exc_type |
| 202 | self.exc_value = args.exc_value |
| 203 | self.exc_traceback = args.exc_traceback |
| 204 | self.thread = args.thread |
| 205 | |
| 206 | def __enter__(self): |
| 207 | self._old_hook = threading.excepthook |
| 208 | threading.excepthook = self._hook |
| 209 | return self |
| 210 | |
| 211 | def __exit__(self, *exc_info): |
| 212 | threading.excepthook = self._old_hook |
| 213 | del self.exc_type |
| 214 | del self.exc_value |
| 215 | del self.exc_traceback |
| 216 | del self.thread |
| 217 | |
| 218 | |
| 219 | def _can_start_thread() -> bool: |
no outgoing calls
no test coverage detected
searching dependent graphs…