From 6580894218a5ade10373ce4c18d41e453c9e1c59 Mon Sep 17 00:00:00 2001 From: Manuel Kroiss Date: Wed, 26 Apr 2017 17:36:56 +0100 Subject: 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 --- src/compiler/python_generator.cc | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/compiler/python_generator.cc b/src/compiler/python_generator.cc index 50ee54abff..278e5072b2 100644 --- a/src/compiler/python_generator.cc +++ b/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; -- cgit v1.2.3