Make generated python files compatible with Cython (#11011)

Replace access to variables created in globals() by explicit access to the globals() array. This avoids static analysis of the code to error out on those unknown variables, and make the files cythonable.

Fixes #10800

Closes #11011

COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/11011 from vthib:10800-cython-compatibility 705da40d5c
PiperOrigin-RevId: 493379473
pull/11175/head
Vincent Thiberville 2 years ago committed by Copybara-Service
parent 7935932356
commit 9aa5272420
  1. 11
      src/google/protobuf/compiler/python/generator.cc

@ -298,6 +298,7 @@ bool Generator::Generate(const FileDescriptor* file,
PrintTopBoilerplate();
PrintImports();
PrintFileDescriptor();
printer_->Print("_globals = globals()\n");
if (GeneratingDescriptorProto()) {
printer_->Print("if _descriptor._USE_C_DESCRIPTORS == False:\n");
printer_->Indent();
@ -312,7 +313,7 @@ bool Generator::Generate(const FileDescriptor* file,
// Find the message descriptors first and then use the message
// descriptor to find enums.
printer_->Print(
"_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())\n");
"_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)\n");
if (GeneratingDescriptorProto()) {
printer_->Outdent();
}
@ -323,7 +324,7 @@ bool Generator::Generate(const FileDescriptor* file,
}
printer_->Print(
"_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, '$module_name$', "
"globals())\n",
"_globals)\n",
"module_name", module_name);
printer.Print("if _descriptor._USE_C_DESCRIPTORS == False:\n");
printer_->Indent();
@ -345,7 +346,7 @@ bool Generator::Generate(const FileDescriptor* file,
printer_->Outdent();
if (HasGenericServices(file)) {
printer_->Print(
"_builder.BuildServices(DESCRIPTOR, '$module_name$', globals())\n",
"_builder.BuildServices(DESCRIPTOR, '$module_name$', _globals)\n",
"module_name", module_name);
}
@ -1231,8 +1232,8 @@ void Generator::PrintSerializedPbInterval(const DescriptorT& descriptor,
GOOGLE_CHECK_GE(offset, 0);
printer_->Print(
"$name$._serialized_start=$serialized_start$\n"
"$name$._serialized_end=$serialized_end$\n",
"_globals['$name$']._serialized_start=$serialized_start$\n"
"_globals['$name$']._serialized_end=$serialized_end$\n",
"name", name, "serialized_start", absl::StrCat(offset), "serialized_end",
absl::StrCat(offset + sp.size()));
}

Loading…
Cancel
Save