Skip to content

Instantly share code, notes, and snippets.

@aliles
Created December 18, 2013 11:33
Show Gist options
  • Save aliles/8020898 to your computer and use it in GitHub Desktop.
Save aliles/8020898 to your computer and use it in GitHub Desktop.
Demonstrate how to use Python's weakref module to ensure that filemagic Magic objects are closed before begin garbage collected when encapsulated inside a container object.
import magic
import weakref
class Container(object):
def __init__(self):
_magic = magic.Magic()
cleanup = lambda _: _magic.close()
self._magic_weakref = weakref.ref(self, cleanup)
self._magic = _magic
if __name__ == "__main__":
con = Container()
import magic
class Container(object):
def __init__(self):
self._magic = magic.Magic()
if __name__ == "__main__":
con = Container()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment