diff options
author | Manuel Kroiss <makro@google.com> | 2017-04-26 17:36:56 +0100 |
---|---|---|
committer | Manuel Kroiss <makro@google.com> | 2017-04-27 23:42:25 +0100 |
commit | 6580894218a5ade10373ce4c18d41e453c9e1c59 (patch) | |
tree | 771bcfc46e2691c604b5f99df10e857ce18676a0 /src/compiler/python_generator.cc | |
parent | e7c31edb555399b699261cb6e0b9f83fb3d6d9d9 (diff) |
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
Diffstat (limited to 'src/compiler/python_generator.cc')
-rw-r--r-- | src/compiler/python_generator.cc | 12 |
1 files changed, 10 insertions, 2 deletions
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; |