backports-weakref

1.0.post1 · maintenance · verified Sat Apr 11

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

Install

Imports

Quickstart

This example demonstrates how to use the backported `finalize` to ensure a cleanup function is called when an object is garbage collected. This is particularly useful for managing external resources like file handles or network connections.

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.")

view raw JSON →