Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make protoc generated python stub file to include package name in import

I use the protoc tool, from grpc-tools package (ver. 1.43.0) with python 3.8.10 to generate the data types and client and server stubs for my proto3 service. The generated file containing the stubs (ending in '_grpc.py') imports the generated file containing the message data types using an import statement with no package name: 'import <my_service_name>_pb2.py'. If I understand correctly, in order for this import to work properly in python 3 when the generated code is being included in a package, this import needs to include the name of the package containing it: 'from <my_containing_package> import <my_service_name>_pb2.py'. Is there a way to make protoc generate this import with the package name I require?

P.S. I'm currently using sed to post edit the generated file to add the package name, so only interested, here, in a way to make protoc generate the correct form for python 3 in the first place.

like image 722
sinjin Avatar asked Oct 29 '25 04:10

sinjin


1 Answers

The official recommendation is to add the Python Proto Package folder to the Path ( September 2023 )

You can do this with the code below in __init__.py

import os
import sys

sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

https://github.com/dydxprotocol/v4-chain/pull/215

like image 95
Alexey Prokopenko Avatar answered Oct 30 '25 21:10

Alexey Prokopenko