{"id":3421,"library":"backports-weakref","title":"backports-weakref","description":"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.","status":"maintenance","version":"1.0.post1","language":"python","source_language":"en","source_url":"https://github.com/pjdelport/backports.weakref","tags":["weak references","backport","memory management","garbage collection","python2","python3"],"install":[{"cmd":"pip install backports-weakref","lang":"bash","label":"Install with pip"}],"dependencies":[],"imports":[{"symbol":"finalize","correct":"from backports.weakref import finalize"}],"quickstart":{"code":"import sys\nimport os\nfrom backports.weakref import finalize\n\nclass Resource:\n    def __init__(self, name):\n        self.name = name\n        print(f\"Resource '{self.name}' created.\")\n\n    def cleanup(self, message):\n        print(f\"Cleanup for '{self.name}': {message}\")\n\n# Create a resource\nmy_resource = Resource(\"DatabaseConnection\")\n\n# Register a finalizer to clean up when my_resource is garbage collected\n# The finalizer ensures cleanup even if `my_resource` goes out of scope.\nfinalizer = finalize(my_resource, my_resource.cleanup, \"Closing connection...\")\n\nprint(\"Resource created, finalizer registered.\")\n\n# Simulate removing the strong reference\ndel my_resource\n\n# The finalizer will be called when the object is garbage collected.\n# Force garbage collection for demonstration (not typically needed in real code)\nimport gc\ngc.collect()\n\nprint(\"Program finished.\")","lang":"python","description":"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."},"warnings":[{"fix":"For Python 3.4+ environments, use `import weakref` directly, as the functionality is built-in.","message":"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.","severity":"deprecated","affected_versions":"< 3.4 (relevant), >= 3.4 (superseded)"},{"fix":"Ensure the object type supports weak references. Custom classes (without `__slots__` preventing `__weakref__`) and certain built-in types (e.g., instances of user-defined classes, functions) generally work.","message":"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`.","severity":"gotcha","affected_versions":"All Python versions (including those using this backport)"},{"fix":"Ensure finalizer callbacks are robust and handle their own internal errors to prevent silent failures. Avoid complex or potentially error-prone logic within callbacks.","message":"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.","severity":"gotcha","affected_versions":"All Python versions using `weakref.finalize` (including this backport)"},{"fix":"Check your Python version. For Python 3.4+, use the native `weakref.WeakMethod`. For older Python versions, if `WeakMethod` is required, a different dedicated backport or a custom implementation might be necessary.","message":"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.","severity":"gotcha","affected_versions":"Python 2.7, Python 3.0-3.3"}],"env_vars":null,"search_vec":"'1.0':38 '2.7':52 '2017':45 '3':55 '3.4':32 '3.6':59 'backport':2,7,19,23,70 'backports-weakref':1 'collect':74 'current':35 'featur':10,66 'function':24 'garbag':73 'includ':64 'introduc':29 'last':41 'librari':34 'manag':72 'memori':71 'modul':16 'namespac':20 'nativ':67 'new':9 'newer':61 'packag':5 'post1':39 'primari':22 'primarili':48 'provid':6 'python':12,31,51,54,62 'python2':75 'python3':76 'refer':69 'releas':42 'septemb':44 'standard':14 'use':49 'version':37,56,63 'weak':68 'weakref':3,15 'weakref.finalize':26","created_at":"2026-04-11T17:28:23.668019+00:00","updated_at":"2026-04-16T14:22:45.098194+00:00","problems":[{"fix":"Ensure the package is installed using pip: `pip install backports-weakref`.","cause":"The top-level 'backports' namespace package, which contains 'backports.weakref', is not installed or not accessible in the current Python environment.","error":"ModuleNotFoundError: No module named 'backports'"},{"fix":"Install the package: `pip install backports-weakref`. If already installed, check your Python path and virtual environment.","cause":"This error occurs when a module attempts to `from backports.weakref import finalize` but the `backports.weakref` subpackage is not found, often implying the `backports-weakref` package was not installed or is incorrectly configured in the environment.","error":"ImportError: No module named weakref"},{"fix":"Reinstall the package to ensure all components are correctly placed: `pip uninstall backports-weakref && pip install backports-weakref`.","cause":"The 'backports' namespace package is found, but the 'weakref' submodule or its contents are not correctly installed or recognized within it, possibly due to a corrupted installation or a path issue.","error":"AttributeError: module 'backports' has no attribute 'weakref'"},{"fix":"Verify that `backports-weakref` is installed and up-to-date (`pip install --upgrade backports-weakref`). Also, double-check the import statement for typos: `from backports.weakref import finalize`.","cause":"While the `backports.weakref` module is found, the specific name `finalize` cannot be imported, which might indicate a typo, an attempt to import from an older version of `backports.weakref` that didn't expose `finalize`, or an issue with the module's contents.","error":"ImportError: cannot import name 'finalize' from 'backports.weakref'"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"1.0.post1","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/pjdelport/backports.weakref","docs":null,"changelog":null,"pypi":"https://pypi.org/project/backports-weakref/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":[],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-29","next_check":"2026-07-28","install_tag":null}}