From f9764b9c5d0a2875476fe237dfb6fd237889d7c2 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 8 Jan 2017 01:37:23 +0200 Subject: [PATCH] Replace destructor with context manager (#223) * Make TorchNeuralNet a context manager. Add __enter__/__exit__ method to kill Torch subprocess * Update doc for the TorchNeuralNet * Fix code snippets * Update doc for enter/exit methods * Format docstring for enter/exit methods --- openface/torch_neural_net.py | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/openface/torch_neural_net.py b/openface/torch_neural_net.py index 6768f39..f155173 100644 --- a/openface/torch_neural_net.py +++ b/openface/torch_neural_net.py @@ -32,7 +32,27 @@ os.environ['TERM'] = 'linux' class TorchNeuralNet: - """Use a `Torch `_ subprocess for feature extraction.""" + """ + Use a `Torch `_ subprocess for feature extraction. + + It also can be used as context manager using `with` statement. + + .. code:: python + + with TorchNeuralNet(model=model) as net: + # code + + or + + .. code:: python + + net = TorchNeuralNet(model=model) + with net: + # use Torch' neuronal network + + In this way Torch processes will be closed at the end of the `with` block. + `PEP 343 `_ + """ #: The default Torch model to use. defaultModel = os.path.join(myDir, '..', 'models', 'openface', 'nn4.small2.v1.t7') @@ -68,10 +88,15 @@ class TorchNeuralNet: self.p.kill() atexit.register(exitHandler) - def __del__(self): - """__del__(self) + def __enter__(self): + """Part of the context manger' protocol. See PEP 343""" + return self - Kill the Lua subprocess. + def __exit__(self, exc_type, exc_value, traceback): + """ + Clean up resources when leaves `with` block. + + Kill the Lua subprocess to prevent zombie processes. """ if self.p.poll() is None: self.p.kill()