Skip to content

Commit e53b485

Browse files
Make Device a context manager (support with-statement)
1 parent d3c077c commit e53b485

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

src/__init__.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,9 +257,27 @@ def destroy(self):
257257
underlying file descriptor. This method must be called exactly once for
258258
each created device.
259259
260+
Alternatively, use ``with``-statement for example as follows:
261+
>>> with uinput.Device([uinput.KEY_A]) as device:
262+
>>> device.emit_click(uinput.KEY_A)
263+
264+
This ensures ``Device.destroy()`` is called at the end of the block.
265+
260266
"""
261-
_libsuinput.suinput_destroy(self.__uinput_fd)
262-
self.__uinput_fd = -1
267+
try:
268+
_libsuinput.suinput_destroy(self.__uinput_fd)
269+
finally:
270+
## There's probably nothing more we can do. If the suinput_destroy()
271+
## has failed once, it almost certainly will fail again. Let's just
272+
## reset the descriptor and give up.
273+
self.__uinput_fd = -1
274+
275+
def __enter__(self):
276+
return self
277+
278+
def __exit__(self, *args):
279+
self.destroy()
280+
return False ## Not handling any exceptions.
263281

264282
def __del__(self):
265283
if self.__uinput_fd >= 0:

0 commit comments

Comments
 (0)