Skip to main content

``weakref`` for threads.

Project description

Allows threads in Python to create “weak references” to themselves that detect when the thread is no longer running, similar to how a weak reference detects when its referent object is no longer alive.

Provides a lightweight way for one or more independent pieces of code to register per-thread cleanup callbacks without coordination.

Versioning

This library’s version numbers follow the SemVer 2.0.0 specification.

Installation

pip install threadref

Usage

Import:

import threadref

ref

Create a reference to the current thread, with a callback that will fire when the thread exits:

reference = threadref.ref(lambda reference: ...)

threadref.ref mirrors weakref.ref, except that:

  1. It references the thread that constructed it instead of taking a referent argument.

  2. It starts returning None instead of the threading.Thread object for its thread once the thread stops running, not once that object stops being alive.

So just like weakref.ref, threadref.ref instances must still be alive when their referent thread stops running, or their callback will not be called.

finalize

Create a finalizer for the current thread, which will be called when the thread exits:

finalizer = threadref.finalize(function, *args, **kwargs)

threadref.finalize mirrors weakref.finalize, except that:

  1. It references the thread that constructed it instead of taking a referent argument.

  2. In all cases where weakref.finalize returns the tuple (object, function, args, kwargs), it returns the tuple (thread, function, args, kwargs) instead.

  3. It starts returning None once the thread stops running.

The finalizer remains alive on its own as long as it needs to, so this is a simpler and nicer interface in the typical case of registering cleanup functions.

Portability

Internally, threadref is just a weak reference to a thread local variable, and this trick seems to only work on CPython implementations with the C implementation of threading.local.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

threadref-1.1.1.tar.gz (4.3 kB view hashes)

Uploaded Source

Built Distributions

threadref-1.1.1-py38-none-any.whl (4.0 kB view hashes)

Uploaded Python 3.8

threadref-1.1.1-py34-none-any.whl (4.1 kB view hashes)

Uploaded Python 3.4

threadref-1.1.1-py2.py30-none-any.whl (3.8 kB view hashes)

Uploaded Python 2 Python 3.0

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page