Skip to content

Commit

Permalink
Make generated python files compatible with Cython (#11011)
Browse files Browse the repository at this point in the history
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=#11011 from vthib:10800-cython-compatibility 705da40
PiperOrigin-RevId: 493379473
  • Loading branch information
vthib authored and copybara-github committed Dec 6, 2022
1 parent 7935932 commit 9aa5272
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/google/protobuf/compiler/python/generator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
}
Expand All @@ -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();
Expand All @@ -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);
}

Expand Down Expand Up @@ -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()));
}
Expand Down

0 comments on commit 9aa5272

Please sign in to comment.