apmorton / pyhidapi

hidapi bindings in ctypes
MIT License
111 stars 42 forks source link

Device class can be used as context manager #35

Closed mayanksuman closed 4 years ago

mayanksuman commented 4 years ago

HID device need to be closed after opening them. A perfect use case for context manager.

A sample code is added in README.md for using Device() as context manager.

apmorton commented 4 years ago

Happy to merge this after a small change.

Context managers exit function is only intended to clean up - it should not rethrow. See the docs for more details.

Docs

The exit method here should just call self.close()

mayanksuman commented 4 years ago

exit() now return False in that case and let python display the traceback.

apmorton commented 4 years ago

Closer, but not quite.

The if an return should be removed entirely.

The only return value from an __exit__ that is relevant is a truthy object if you want to suppress an exception. Since we don't, we can return nothing (which results in a return of None and evaluates to false).

The code you have now is basically

return False if thing else None, which is rather redundant.

apmorton commented 4 years ago

Thanks