backports-weakref
This package provides backports of new features in Python's standard `weakref` module under the `backports` namespace. Its primary backported functionality is `weakref.finalize`, which was introduced in Python 3.4. The library, currently at version `1.0.post1`, was last released in September 2017 and is primarily useful for Python 2.7 and Python 3 versions up to 3.6, as newer Python versions include these features natively.
Warnings
- deprecated This library backports `weakref.finalize` (new in Python 3.4) and other features. For Python 3.4 and newer, these features are part of the standard `weakref` module, making this backport largely unnecessary for modern Python development.
- gotcha Standard Python built-in types such as `int`, `str`, `list`, `dict`, and `tuple` generally do not support weak references, even when subclassed. Attempting to create a weak reference to such an object will raise a `TypeError`.
- gotcha Exceptions raised by `weakref.finalize` callbacks during garbage collection are typically caught and printed to `sys.stderr`, but they cannot be propagated or handled by standard `try...except` blocks in the main program flow.
- gotcha While the standard `weakref` module includes `WeakMethod` (from Python 3.4+), `backports.weakref` explicitly lists only `weakref.finalize` as its backported functionality. Users expecting `WeakMethod` might find it missing from this backport.
Install
-
pip install backports-weakref
Imports
- finalize
from backports.weakref import finalize
Quickstart
import sys
import os
from backports.weakref import finalize
class Resource:
def __init__(self, name):
self.name = name
print(f"Resource '{self.name}' created.")
def cleanup(self, message):
print(f"Cleanup for '{self.name}': {message}")
# Create a resource
my_resource = Resource("DatabaseConnection")
# Register a finalizer to clean up when my_resource is garbage collected
# The finalizer ensures cleanup even if `my_resource` goes out of scope.
finalizer = finalize(my_resource, my_resource.cleanup, "Closing connection...")
print("Resource created, finalizer registered.")
# Simulate removing the strong reference
del my_resource
# The finalizer will be called when the object is garbage collected.
# Force garbage collection for demonstration (not typically needed in real code)
import gc
gc.collect()
print("Program finished.")