Implement optional scalars for Python (#7318)

* Implement optional scalars for Python

* Use == for integer comparison, remove empty line

* Fix optional type hint

Co-authored-by: Caleb Zulawski <caleb.zulawski@caci.com>
This commit is contained in:
Caleb Zulawski
2022-06-13 09:16:00 -04:00
committed by GitHub
parent 11a1988705
commit 49e1ea3335
8 changed files with 594 additions and 10 deletions

View File

@@ -207,7 +207,9 @@ class PythonGenerator : public BaseGenerator {
if (is_bool) { getter = "bool(" + getter + ")"; }
code += Indent + Indent + Indent + "return " + getter + "\n";
std::string default_value;
if (is_bool) {
if (field.IsScalarOptional()) {
default_value = "None";
} else if (is_bool) {
default_value = field.value.constant == "0" ? "False" : "True";
} else {
default_value = IsFloat(field.value.type.base_type)
@@ -593,9 +595,13 @@ class PythonGenerator : public BaseGenerator {
code += field_var;
}
code += ", ";
code += IsFloat(field.value.type.base_type)
? float_const_gen_.GenFloatConstant(field)
: field.value.constant;
if (field.IsScalarOptional()) {
code += "None";
} else if (IsFloat(field.value.type.base_type)) {
code += float_const_gen_.GenFloatConstant(field);
} else {
code += field.value.constant;
}
code += ")\n";
if (!parser_.opts.one_file) {
@@ -868,7 +874,9 @@ class PythonGenerator : public BaseGenerator {
std::string GetDefaultValue(const FieldDef &field) const {
BaseType base_type = field.value.type.base_type;
if (IsBool(base_type)) {
if (field.IsScalarOptional()) {
return "None";
} else if (IsBool(base_type)) {
return field.value.constant == "0" ? "False" : "True";
} else if (IsFloat(base_type)) {
return float_const_gen_.GenFloatConstant(field);
@@ -991,6 +999,9 @@ class PythonGenerator : public BaseGenerator {
default:
// Scalar or sting fields.
field_type = GetBasePythonTypeForScalarAndString(base_type);
if (field.IsScalarOptional()) {
field_type = "Optional[" + field_type + "]";
}
break;
}