fix: py_proto_library: append to PYTHONPATH less (#1553)
Only append the `[proto_root]` to PYTHONPATH when it's actually
necessary, i.e. when the generated Python modules are under
_virtual_imports. Do no append it in the general case, when
`[proto_root]` is just the repository root.
This makes it much less likely that adding a transitive dep on a
`py_proto_library` will reorder the `PYTHONPATH`. Such reordering is
undesirable because it may lead to import errors.
Fixes #1551
diff --git a/python/private/proto/py_proto_library.bzl b/python/private/proto/py_proto_library.bzl
index 116590f..76dd224 100644
--- a/python/private/proto/py_proto_library.bzl
+++ b/python/private/proto/py_proto_library.bzl
@@ -107,10 +107,13 @@
return [
_PyProtoInfo(
imports = depset(
- # Adding to PYTHONPATH so the generated modules can be imported.
- # This is necessary when there is strip_import_prefix, the Python
- # modules are generated under _virtual_imports.
- [proto_root],
+ # Adding to PYTHONPATH so the generated modules can be
+ # imported. This is necessary when there is
+ # strip_import_prefix, the Python modules are generated under
+ # _virtual_imports. But it's undesirable otherwise, because it
+ # will put the repo root at the top of the PYTHONPATH, ahead of
+ # directories added through `imports` attributes.
+ [proto_root] if "_virtual_imports" in proto_root else [],
transitive = [dep[PyInfo].imports for dep in api_deps],
),
runfiles_from_proto_deps = runfiles_from_proto_deps,