boppreh / keyboard

Hook and simulate global keyboard events on Windows and Linux.
MIT License
3.8k stars 433 forks source link

Add type hints #505

Open Avasam opened 2 years ago

Avasam commented 2 years ago

Please add type hints to the functions

image

boppreh commented 2 years ago

Unfortunately one of the selling points of the library is compatibility with older Python versions, often necessary in some enterprise environments. Right now the library supports even Python 2.7, and type hints would eliminate that feature.

I'll continue monitoring community usage, and if Python 2-3.4 support is not necessary anymore, I'll drop it and add type hints.

Edit: I guess I could add at least a stub file for MyPy without breaking compatibility. I'll look into it.

Avasam commented 2 years ago

.pyi files (type stubs) are the way to go in this case. Here's auto generated ones by Pylance. I've already filled in some that I use, namely send(), hook_key(), read_event() , KeyboardEvent (partial attributes), key_to_scan_codes() (partial return type) : keyboard.zip Or the following typings folder which I'm updating as I'm using it: https://github.com/Toufool/Auto-Split/tree/2.0.0/typings/keyboard

Avasam commented 2 years ago

Right now the library supports even Python 2.7, and type hints would eliminate that feature.

@boppreh You can have inline typing in Python2 code by using type comments https://mypy.readthedocs.io/en/stable/python2.html Or by making stub files, but inline types have the advantage that they can be inferred (so you don't need to precisely type everything), and you can then typecheck the code using mypy and/or Pyright.

Avasam commented 2 years ago

3rd party keyboard type stubs (by myself) have been added to typeshed https://github.com/python/typeshed/pull/8666 Of course, this will only support the version available on PyPI, which is now far behind master.

It'd be best if the stubs were part of keyboard itself. You should be able to use them directly from typeshed (and they should be fairly accurate). Although they also wouldn't be removed from typeshed until a PyPI release of keyboard includes the stubs.

Ultimately, the best scenario is to have inline typing directly, as it reduces chances of desync between stubs and implementation, and allows for easy type-checking in the CI and during development. However, due to the Python2 support requirement, inline type comments may be annoying, and will be more complicated to support multiple Python version while trying to keep typing as accurate as possible depending on what said version supports.