Fix python imports in gRPC generated python code

This changes the import style for proto dependencies from a) to b).
a) "import a.b.c as x"
b) "from a.b import c as x"

Using statement a) causes problems when using __init__ files. If module
"a.b" has an __init__.py file which is importing the python generated
grpc code "a.b.d", then we cannot import a module named "a.b.c" because
the module "a.b" does not exist yet. In this case python will throw:
AttributeError: 'module' object has no attribute 'b'

This PR adapts the code to use the same logic as in:
/google/protobuf/compiler/python/python_generator.cc
pull/10862/head
Manuel Kroiss 8 years ago
parent e7c31edb55
commit 6580894218
  1. 12
      src/compiler/python_generator.cc

@ -622,9 +622,17 @@ bool PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
for (StringPairSet::iterator it = imports_set.begin();
it != imports_set.end(); ++it) {
var["ModuleName"] = std::get<0>(*it);
auto module_name = std::get<0>(*it);
var["ModuleAlias"] = std::get<1>(*it);
out->Print(var, "import $ModuleName$ as $ModuleAlias$\n");
const size_t last_dot_pos = module_name.rfind('.');
if (last_dot_pos == grpc::string::npos) {
var["ImportStatement"] = "import " + module_name;
} else {
var["ImportStatement"] = "from " + module_name.substr(0, last_dot_pos) +
" import " +
module_name.substr(last_dot_pos + 1);
}
out->Print(var, "$ImportStatement$ as $ModuleAlias$\n");
}
}
return true;

Loading…
Cancel
Save