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.