Created
December 18, 2013 11:33
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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