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

Class Finalize

Lib/multiprocessing/util.py:253–336  ·  view source on GitHub ↗

Class which supports object finalization using weakrefs

Source from the content-addressed store, hash-verified

251
252
253class Finalize(object):
254 '''
255 Class which supports object finalization using weakrefs
256 '''
257 def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None):
258 if (exitpriority is not None) and not isinstance(exitpriority,int):
259 raise TypeError(
260 "Exitpriority ({0!r}) must be None or int, not {1!s}".format(
261 exitpriority, type(exitpriority)))
262
263 if obj is not None:
264 self._weakref = weakref.ref(obj, self)
265 elif exitpriority is None:
266 raise ValueError("Without object, exitpriority cannot be None")
267
268 self._callback = callback
269 self._args = args
270 self._kwargs = kwargs or {}
271 self._key = (exitpriority, next(_finalizer_counter))
272 self._pid = os.getpid()
273
274 _finalizer_registry[self._key] = self
275
276 def __call__(self, wr=None,
277 # Need to bind these locally because the globals can have
278 # been cleared at shutdown
279 _finalizer_registry=_finalizer_registry,
280 sub_debug=sub_debug, getpid=os.getpid):
281 '''
282 Run the callback unless it has already been called or cancelled
283 '''
284 try:
285 del _finalizer_registry[self._key]
286 except KeyError:
287 sub_debug('finalizer no longer registered')
288 else:
289 if self._pid != getpid():
290 sub_debug('finalizer ignored because different process')
291 res = None
292 else:
293 sub_debug('finalizer calling %s with args %s and kwargs %s',
294 self._callback, self._args, self._kwargs)
295 res = self._callback(*self._args, **self._kwargs)
296 self._weakref = self._callback = self._args = \
297 self._kwargs = self._key = None
298 return res
299
300 def cancel(self):
301 '''
302 Cancel finalization of the object
303 '''
304 try:
305 del _finalizer_registry[self._key]
306 except KeyError:
307 pass
308 else:
309 self._weakref = self._callback = self._args = \
310 self._kwargs = self._key = None

Callers 2

_start_threadMethod · 0.85
get_temp_dirFunction · 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…