Automatically add type hints for API Object attributes #141
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Adds a script,
scripts/generate_attribute_types.py
, which automatically generates type hints for attributes in API objects. Also adds the generated type hints, and a test workflow step to check that types are up to date.There are two main motivations for this:
The type generation scripts runs the test_api test suite, profiles it to see the actual types of the attributes at runtime, and uses that to patch the module file with those actual types. This is inspired by (and uses the internals of) MonkeyType. MonkeyType does not do attribute types, which is why we had to hand-roll this implementation. The module patching functionality uses LibCST, and also patches missing functionality in LibCST, namely Instagram/LibCST#323 and Instagram/LibCST#1159.
The reason this is so complicated is that all of the classes in apiobject.py have attributes dynamically injected at runtime from the JSON response returned by AllSpice Hub. These can change with every version of AllSpice Hub. So, any system to generate types must be able to detect when types are changed upstream and update them. This script fulfils that, and in fact this PR adds a CI check to ensure that the types that are checked in match what ASH is sending.
There are still a few rough edges in this system:
Any
s.But all of that can be fixed with more work in the future, and the script is plenty useful as is.