Skip to content

Use relative imports for same-package pb2 modules#2

Open
LysanderGG wants to merge 1 commit intomainfrom
fix/relative-imports
Open

Use relative imports for same-package pb2 modules#2
LysanderGG wants to merge 1 commit intomainfrom
fix/relative-imports

Conversation

@LysanderGG
Copy link

Summary

  • When a generated twirp file imports a _pb2 module from the same package directory, emit a relative import (from . import v1_pb2) instead of an absolute one (from crypto import v1_pb2)
  • Cross-package imports (e.g. google.protobuf) remain absolute
  • Fixes ModuleNotFoundError when generated files are nested under a different top-level package (e.g. bridge.proto.crypto.v1_twirp trying from crypto import v1_pb2)

Context

In the marketdata-pipeline bridge, protos are at crypto/v1.proto (relative to --proto_path) but the generated Python files live under bridge/proto/crypto/. The absolute import from crypto import v1_pb2 fails because crypto is not a top-level Python package.

Changes

  • import_builder.go: track current file's directory, emit . when import path matches
  • generator.go: pass current filename to newImportBuilder
  • generator_test.go: updated tests covering same-package (relative) and cross-package (absolute) cases

Test plan

  • Go unit tests pass
  • Built plugin and regenerated marketdata-pipeline bridge proto files
  • Verified all same-package imports use from . import
  • Verified cross-package imports (google.protobuf) stay absolute
  • Bridge starts and serves healthcheck with the new generated code

🤖 Generated with Claude Code

When a twirp file imports a pb2 module from the same package directory,
generate a relative import (from . import v1_pb2) instead of an absolute
one (from crypto import v1_pb2). This fixes ModuleNotFoundError when
generated files are nested under a different top-level package.

Cross-package imports (e.g. google.protobuf) remain absolute.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@LysanderGG
Copy link
Author

This is a plugin-only change — no runtime modification needed. After merging, a new protoc-gen-twirpy release tag (e.g. protoc-gen-twirpy/0.3.0-dev.2) should be created to publish the updated binary via goreleaser.

@LysanderGG LysanderGG requested review from a team and MiLk March 17, 2026 07:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant