Skip to main content

A Descriptor class implementing weakref properties in Python

Project description

Add a property that acts like a normal attribute, but keeps a weak reference to anything that is assigned to it.

Example:

First let’s define WeakValue using WeakProperty and SomeClass that will be weakly referenced:

>>> import weakref_property
>>> import gc

>>> class WeakValue(object):
...     value = weakref_property.WeakProperty('value')

>>> class SomeClass(object):
...     pass

You can assign and retrieve a value:

>>> a = SomeClass()
>>> obj = WeakValue()
>>> obj.value = a
>>> obj.value  # doctest: +ELLIPSIS
<__main__.SomeClass object at ...>

But it is kept as a weakref, so it can get collected. If it is collected, the property returns None:

>>> del a
>>> gc.collect()  # force gc to collect `a` object
0
>>> obj.value

You can also delete the value completelly:

>>> del obj.value
>>> obj.value
Traceback (most recent call last):
    ...
AttributeError: 'WeakValue' object has no attribute 'value'

Sadly, weakrefs do not work on tuples, ints and not-subclassed lists and dicts:

>>> obj.value = []
Traceback (most recent call last):
    ...
TypeError: cannot create weak reference to 'list' object

Project details


Release history Release notifications | RSS feed

This version

0.1

Download files

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

Source Distribution

weakref_property-0.1.tar.gz (14.4 kB view details)

Uploaded Source

File details

Details for the file weakref_property-0.1.tar.gz.

File metadata

File hashes

Hashes for weakref_property-0.1.tar.gz
Algorithm Hash digest
SHA256 258180f09fc0eb19a4483b642796c9000a31e0f25491635cf4e91850b91ea32d
MD5 3943ab8ab26bdb5bf17d329e202b3f58
BLAKE2b-256 d032fe976e59a132a52ff79e3a714b8f938a518205ddf490634dfac39aed2194

See more details on using hashes here.

Supported by

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