Pr0Ger/protobuf3

Compiler produces absolute instead of explicit relative imports

Opened this issue · 1 comments

dhrmn commented

For instance, assume a package structure like the following

mytool.py
-> protobuf/msg.proto
-> protobuf/base_msg.proto

mytool.py

import protobuf.msg

protobuf/msg.proto

import "base_msg.proto";
message Msg { optional BaseMsg base = 1; }

protobuf/base_msg.proto

message BaseMsg { optional uint32 id = 1; }

The protoc compiler produces an absolute import of base_msg:
protobuf/msg.py

from base_msg import BaseMsg

If I now execute mytool.py, I get an ImportError:

$ python3 mytool.py
Traceback (most recent call last):
File "mytool.py", line 2, in
import protobuf.msg
File "/home/monitor/mytool/protobuf/msg.py", line 1, in
from base_msg import BaseMsg
ImportError: No module named 'base_msg'

It works fine if the generated code uses an explicit relative import instead of the absolute import:

from .base_msg import BaseMsg

dhrmn commented

This patch makes it work:

 $ diff -u python3.4/site-packages/protobuf3/compiler/__init__.py{.orig,}
 --- python3.4/site-packages/protobuf3/compiler/__init__.py.orig 2016-06-07 08:51:11.000000000 +0000
 +++ python3.4/site-packages/protobuf3/compiler/__init__.py      2016-06-23 13:25:50.108000000 +0000
 @@ -145,7 +145,7 @@
              top_level_name = type_name.split('.')[0]

              if top_level_name not in self.__top_level_elements:
 -                file_to_import = splitext(self.__tle_map[top_level_name])[0].replace('/', '.')
 +                file_to_import = '.' + splitext(self.__tle_map[top_level_name])[0].replace('/', '.')
                  if file_to_import not in self.__imports:
                      self.__imports[file_to_import] = {top_level_name}
                  else: