mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-03 12:21:23 +00:00
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:
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user