Skip to content

fin_wrap

Finalizer wrapper for automatic cleanup of objects.

The fin_wrap class wraps an object stored on a parent object and registers a weakref finalizer that calls a cleanup function when the wrapper is garbage collected. This ensures resources are released when the wrapped object is no longer referenced.

Classes:

Name Description
fin_wrap

Wraps an object on a parent with a weakref finalizer for cleanup.

FinWrapper

Wraps an object with attribute delegation via fin_wrap.

Functions:

Name Description
fin_wrap_np

Wraps an object in a simple namespace with a finalizer.

Example
import gc
from py_misc_utils import fin_wrap as fw

class Res:

  def close(self):
    print('closed')

owner = type('Owner', (), {})()
res = Res()

fw.fin_wrap(owner, 'res', res, finfn=res.close)
del owner.res  # Runs the finalizer without waiting for GC.
gc.collect()

fin_wrap

Wrapper registering a weakref finalizer on a parent attribute.

Parameters:

Name Type Description Default
parent

The object the wrapped attribute is stored on.

required
name

The attribute name the wrapped object is stored under.

required
obj

The object to wrap.

required
finfn

A callable to invoke when the wrapper is garbage collected.

None
cleanup

If True, the wrapped object is cleaned up when the wrapper attribute is removed before garbage collection.

False
Source code in py_misc_utils/fin_wrap.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class fin_wrap:
  """Wrapper registering a weakref finalizer on a parent attribute.

  Args:
    parent: The object the wrapped attribute is stored on.
    name: The attribute name the wrapped object is stored under.
    obj: The object to wrap.
    finfn: A callable to invoke when the wrapper is garbage collected.
    cleanup: If True, the wrapped object is cleaned up when the wrapper
      attribute is removed before garbage collection.
  """

  def __init__(self, parent, name, obj, finfn=None, cleanup=False):
    """Initializes a fin_wrap and registers a finalizer.

    Args:
      parent: The object on which to store the wrapped object and finalizer.
      name: The attribute name on parent for the wrapped object.
      obj: The object to wrap. If None, no finalizer is registered and the
        attribute named 'name' is cleared from the parent.
      finfn: A callable to invoke when this wrapper is garbage collected.
      cleanup: If True and obj is None, the finalizer registered for the
        previous wrapper is invoked (running the cleanup function) instead
        of being detached.
    """
    setattr(parent, name, obj)
    fname = _finalizer_name(name)
    if obj is not None:
      tas.check_is_not_none(finfn, msg='Missing finalize function argument')

      setattr(parent, fname, self)
      self._finalizer = weakref.finalize(self, finfn)
    else:
      fwrap = getattr(parent, fname, None)
      if fwrap is not None:
        delattr(parent, fname)
        if cleanup:
          fwrap._finalizer()
        else:
          fwrap._finalizer.detach()

FinWrapper

Object wrapper delegating attribute access to the wrapped object.

The wrapped object is stored under a reserved attribute name and the dunders below forward every other attribute access to it, so that the wrapper transparently behaves like the wrapped object while carrying a finalizer for cleanup. Note that attribute delegation - including dunder lookups such as len - only works for objects exposing a dict (instances of plain classes).

Parameters:

Name Type Description Default
obj

The object to wrap and delegate to.

required
finfn

A callable to invoke when the wrapper is garbage collected.

required
Example
import gc
from py_misc_utils import fin_wrap as fw

class Thing:
  pass

done = []
w = fw.FinWrapper(Thing(), lambda: done.append('closed'))
w.size = 3
assert w.size == 3

del w
gc.collect()
Source code in py_misc_utils/fin_wrap.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class FinWrapper:
  """Object wrapper delegating attribute access to the wrapped object.

  The wrapped object is stored under a reserved attribute name and the
  dunders below forward every other attribute access to it, so that the
  wrapper transparently behaves like the wrapped object while carrying
  a finalizer for cleanup. Note that attribute delegation - including
  dunder lookups such as __len__ - only works for objects exposing a
  __dict__ (instances of plain classes).

  Args:
    obj: The object to wrap and delegate to.
    finfn: A callable to invoke when the wrapper is garbage collected.

  Example:
    import gc
    from py_misc_utils import fin_wrap as fw

    class Thing:
      pass

    done = []
    w = fw.FinWrapper(Thing(), lambda: done.append('closed'))
    w.size = 3
    assert w.size == 3

    del w
    gc.collect()
  """

  def __init__(self, obj, finfn):
    """Initialize the wrapper, registering the finalizer.

    Args:
      obj: The object to wrap and delegate to.
      finfn: A callable to invoke when the wrapper is garbage collected.
    """
    fin_wrap(self, _OBJ_NAME, obj, finfn=finfn)

  def __getattribute__(self, name):
    """Return the attribute of the wrapped object."""
    pd = super().__getattribute__('__dict__')
    obj = pd[_OBJ_NAME]

    return getattr(obj, name)

  def __getattr__(self, name):
    """Return the missing attribute of the wrapped object."""
    pd = super().__getattribute__('__dict__')
    obj = pd[_OBJ_NAME]

    return getattr(obj, name)

  def __setattr__(self, name, value):
    """Set an attribute on the wrapper or on the wrapped object."""
    pd = super().__getattribute__('__dict__')
    if name in _RESERVED_NAMES:
      pd[name] = value
    else:
      obj = pd[_OBJ_NAME]

      setattr(obj, name, value)

  def __delattr__(self, name):
    """Delete an attribute of the wrapper or of the wrapped object."""
    pd = super().__getattribute__('__dict__')
    if name in _RESERVED_NAMES:
      pd.pop(name)
    else:
      obj = pd[_OBJ_NAME]

      delattr(obj, name)

fin_wrap_np(obj, finfn, name='v')

Wrap an object into a fresh namespace object with a finalizer.

Parameters:

Name Type Description Default
obj

The object to wrap.

required
finfn

A callable to invoke when the wrapper is garbage collected.

required
name

Attribute name under which the object is stored.

'v'

Returns:

Type Description

The wrapper object holding the object and the finalizer.

Source code in py_misc_utils/fin_wrap.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def fin_wrap_np(obj, finfn, name='v'):
  """Wrap an object into a fresh namespace object with a finalizer.

  Args:
    obj: The object to wrap.
    finfn: A callable to invoke when the wrapper is garbage collected.
    name: Attribute name under which the object is stored.

  Returns:
    The wrapper object holding the object and the finalizer.
  """
  wrapper = _Wrapper()
  fin_wrap(wrapper, name, obj, finfn=finfn)

  return wrapper