From 9aa5272420f5c666f2dbaba0892b174004c56257 Mon Sep 17 00:00:00 2001 From: Vincent Thiberville Date: Tue, 6 Dec 2022 12:21:14 -0800 Subject: [PATCH] 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 705da40d5c109b0b472483b54917115a5b96b2b8 PiperOrigin-RevId: 493379473 --- src/google/protobuf/compiler/python/generator.cc | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/google/protobuf/compiler/python/generator.cc b/src/google/protobuf/compiler/python/generator.cc index f8a33cc6b4..47662374be 100644 --- a/src/google/protobuf/compiler/python/generator.cc +++ b/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())); }