0

I have the following structure in my Python project:

main.py
sub1/
  __init__.py
  foo.py
  bar.py
  grpc_generated_pb2.py
  grpc_generated_pb2_grpc.py

I have been using the following approach to import local modules, for example,

(in sub1/foo.py)

from sub1 import bar
from sub1 import grpc_generated_pb2_grpc

It works. But now gRPC generated files do the following:

(in sub1/grpc_generated_pb2_grpc.py)

import grpc_generated_pb2 as grpc_generated_pb2

And Python fails to import the module with this error:

ModuleNotFoundError: No module named 'grpc_generated_pb2'

Because it's generated code, I cannot/shouldn't modify it. My question is: why Python cannot import a local module under the same directory without doing from sub1 ?

I think Python should always be able to import a local module from the same directory with a simple import <module_name> (no parent package names). Why doesn't it do that?

UPDATE:

As pointed out by others, there are already similar questions like this one: How do I import from a file in the current directory in Python 3? . However, my question is different in this sense:

Does it mean Google gRPC grpc_tools.protoc failed to generate a working file for Python 3? I am adding gRPC tag hoping to get opinions from gRPC side. Thanks.

user1783732
  • 1,599
  • 5
  • 22
  • 44
  • As a side not, you don't need to write `import grpc_generated_pb2 as grpc_generated_pb2`. It's repetitive. Just write `import grpc_generated_pb2`. – Michael Kolber Jul 26 '19 at 05:21
  • @MichaelKolber this code was generated by `grpc_tools.protoc`. I didn't write it and cannot/should not edit it. – user1783732 Jul 26 '19 at 17:47
  • If I understand PEP 328 (https://www.python.org/dev/peps/pep-0328/) correctly, `protoc` should really generate the import line like `from . import grpc_generated_pb2`, but why gRPC didn't do that? (or should I put them under `sys.path` ?) – user1783732 Jul 26 '19 at 18:10
  • 1
    I found a good answer on GitHub: https://github.com/grpc/grpc/issues/9575#issuecomment-293934506 . Just to share here. – user1783732 Jul 26 '19 at 18:32

0 Answers0