From 578071c00e1026609713114baf7961719f842da7 Mon Sep 17 00:00:00 2001 From: Nick Sweeting Date: Tue, 21 Apr 2020 16:55:29 -0400 Subject: [PATCH] Add context manager zimcreator for automatic finalization --- libzim/libzim.pyx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/libzim/libzim.pyx b/libzim/libzim.pyx index 0af6b396..7427fa82 100644 --- a/libzim/libzim.pyx +++ b/libzim/libzim.pyx @@ -7,6 +7,8 @@ from libcpp.string cimport string from libcpp cimport bool from libcpp.memory cimport shared_ptr, make_shared +from contextlib import contextmanager + import datetime @@ -345,7 +347,15 @@ cdef class ZimCreator: def __repr__(self): return f"{self.__class__.__name__}(filename={self.filename})" - + +@contextmanager +def zimcreator(*args, **kwds): + """Context manager version of ZimCreator that calls .finalize() automatically on exit""" + zimcreator = ZimCreator(*args, **kwds) + try: + yield zimcreator + finally: + zimcreator.finalize() ######################### # ZimFileArticle # @@ -701,4 +711,4 @@ cdef class ZimFileReader: return dereference(search).get_matches_estimated() def __repr__(self): - return f"{self.__class__.__name__}(filename={self.filename})" \ No newline at end of file + return f"{self.__class__.__name__}(filename={self.filename})"