How to strip folder names in py_library imports?

1.8k Views Asked by At

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__)
1

There are 1 best solutions below

3
On BEST ANSWER

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']
)