2

I'm having a problem understanding the python import directories of bazel. Given a tree like this:

.
├── WORKSPACE
├── python_lib_a/
│   ├── BUILD
│   └── src/
│       └── package1/
│           └── folder1/
│               └── some_file.py
└── python_binary_a/
    ├── BUILD
    └── src/
        └── package1/
            └── folder2/
                └── python_binary.py

How can the python_binary.py file import the some_file.py file like this:

from package1.folder1.some_file import SomeClass

I'm pretty new to Bazel, so my google queries could be wrong. I could not find any example of removing/stripping folder names. I'm willing to write custom rules, if necessary. Something like a plugin that changes the folders during compiling.

EDIT: In addition to the accepted answer, I had to do add this to the package1/__init__.py files in both the library and the binary src folders:

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
Melih Yıldız'
  • 415
  • 5
  • 17

1 Answers1

3

There is probably a way to do this but a way that would definitely work is to move the position of your BUILD files

.
├── WORKSPACE
├── python_lib_a/
│   └── src/
│       ├── BUILD
│       └── package1/
│           └── folder1/
│               └── some_file.py
└── python_binary_a/
    └── src/
        ├── BUILD
        └── package1/
            └── folder2/
                └── python_binary.py

Then in python_lib_a it would be like below and called from //python_lib_a/src:package1

py_library(
    name = "package1",
    srcs = glob(
        ["package1**/**/*.py"],
    ),
    imports = ["."],
    visibility = ["//visibility:public"],
)

Then in the other one do

py_library(
    name = "package2",
    srcs = glob(
        ["package1**/**/*.py"],
    ),
    imports = ["."],
    visibility = ["//visibility:public"],
    deps = [ '//python_lib_a/src:package1']
)
AutomatedTester
  • 22,188
  • 7
  • 49
  • 62
  • 2
    I think you could do this without moving the build files. Then you would have `imports = ["src"]`. – Sjoerd Visscher Dec 04 '20 at 12:44
  • Looking at the generated PYTHONPATH environment variable the problem seems to be solved but I still get an import error. This time it is not `No module named package1` but it is `No module named package1.folder2`. – Melih Yıldız' Dec 06 '20 at 22:49
  • solved it by: `import pkgutil; __path__ = pkgutil.extend_path(__path__, __name__)` – Melih Yıldız' Dec 06 '20 at 23:29