-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Use StrEnums
instead of str
for generated constant classes in the ASF APIs
#11176
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
@@ -315,10 +315,11 @@ def get_order(self): | |||
|
|||
|
|||
def generate_service_types(output, service: ServiceModel, doc=True): | |||
output.write("from datetime import datetime\n") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I moved this line so it has the right order from the beginning. I know our formatting will reorder it anyway, but why should it need to :P
def get_class_attrs_from_spec_class(spec_class: type[StrEnum]) -> set[str]: | ||
return {str(spec) for spec in spec_class} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is the only actual code change necessary, which iterates over the classes, now an enum.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice change and really well explained! The stronger the typing the better! 💯
The changes are looking good, they update the scaffold, update all generated APIs, as well as a single issue with the usage of the generated code. 🏅
Motivation
Currently, the scaffolding currently translates the
StringShape
s from the botocore specs to enum string classes, for example:The issue here, from a type checking perspective, is that the values, for example Architecture.x86_64, are not of type Architecture, they are simple strings:
for example, returns:
This is not really an issue for production - they are strings, and the exact type does not really matter after it is serialized anyway. However, when developing, we are hit with fun IDE warnings and mypy also reports it as an error:
Mypy error:
My proposed solution would be to switch those types to StrEnum, a new type of enum introduced with python3.11 (https://docs.python.org/3/library/enum.html#enum.StrEnum). It is only applicable for code not used by the CLI, but our API scaffolds should not be imported from the CLI.
A StrEnum is both an instance of str and enum, and more importantly, the members are also a type of the respective class.
Also, the dunder str and repr methods are those of string, therefore it should be interchangable (we will see how the testing of this PR works out).
Changes
StrEnum
instead ofstr
for generated APIStringShape
s, which will lead to correct types for the enum members.