Skip to content

Commit aab3cee

Browse files
committed
Adjust import logic to account for package names.
1 parent 4183634 commit aab3cee

5 files changed

Lines changed: 102 additions & 18 deletions

File tree

‎python/private/cc/py_extension_macro.bzl‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,16 @@ def py_extension(
2020
**kwargs):
2121
"""Creates a Python extension module.
2222
23+
By default, extensions are created within their workspace package directory
24+
(e.g., `pkg/ext.so`) and imported using standard Python package paths
25+
(e.g., `from pkg import ext`).
26+
27+
To customize import path behavior:
28+
- `imports`: Pass `imports = ["..."]` to append custom search directories to
29+
`sys.path` (matching `py_library`).
30+
- `module_name`: Pass `module_name = "custom_name"` to override the base module
31+
filename.
32+
2333
Args:
2434
name: Target name.
2535
srcs: Optional C/C++ source files to compile directly for this extension.

‎python/private/cc/py_extension_rule.bzl‎

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
11
"""Implementation of the _py_extension_wrapper rule."""
22

3+
load("@bazel_skylib//lib:dicts.bzl", "dicts")
34
load("@rules_cc//cc/common:cc_shared_library_info.bzl", "CcSharedLibraryInfo")
45
load("//python/private:attr_builders.bzl", "attrb")
5-
load("//python/private:attributes.bzl", "COMMON_ATTRS")
6+
load("//python/private:attributes.bzl", "COMMON_ATTRS", "IMPORTS_ATTRS")
67
load("//python/private:builders.bzl", "builders")
78
load("//python/private:py_info.bzl", "PyInfo")
89
load("//python/private:rule_builders.bzl", "ruleb")
910
load("//python/private:toolchain_types.bzl", "PY_CC_TOOLCHAIN_TYPE")
1011

1112
def _py_extension_wrapper_impl(ctx):
1213
module_name = ctx.attr.module_name or ctx.label.name
13-
repo_name = ctx.label.workspace_name or ctx.workspace_name
14-
import_path = repo_name
15-
if ctx.label.package:
16-
import_path = repo_name + "/" + ctx.label.package
1714

1815
cc_toolchain = ctx.toolchains["@bazel_tools//tools/cpp:toolchain_type"].cc
1916
ext = _get_extension(cc_toolchain)
@@ -51,29 +48,51 @@ def _py_extension_wrapper_impl(ctx):
5148
runfiles_builder.add(csl_target[DefaultInfo].default_runfiles)
5249
runfiles = runfiles_builder.build(ctx)
5350

51+
# Resolve imports paths relative to the target package and repository:
52+
# 1. Default (imports = []): No extra search paths are added to sys.path,
53+
# enforcing clean package-qualified imports (e.g. `from foo.bar import ext`).
54+
# 2. Relative paths (e.g. imports = ["."]): Resolved relative to `repo_name/package_name`
55+
# so passing `imports = ["."]` adds the target's package directory to sys.path.
56+
# 3. Absolute paths (starting with "/"): Stripped of leading "/" and resolved relative to runfiles root.
57+
imports_list = []
58+
repo_name = ctx.label.workspace_name or ctx.workspace_name
59+
for path in ctx.attr.imports:
60+
if path.startswith("/"):
61+
imports_list.append(path[1:])
62+
else:
63+
pkg = ctx.label.package
64+
full_path = "{}/{}".format(pkg, path) if pkg else path
65+
if repo_name:
66+
full_path = "{}/{}".format(repo_name, full_path)
67+
imports_list.append(full_path)
68+
5469
return [
5570
DefaultInfo(
5671
files = depset([py_dso]),
5772
runfiles = runfiles,
5873
),
5974
PyInfo(
6075
transitive_sources = depset([py_dso]),
61-
imports = depset([import_path]),
76+
imports = depset(imports_list),
6277
),
6378
]
6479

65-
PY_EXTENSION_WRAPPER_ATTRS = COMMON_ATTRS | {
66-
"libc": lambda: attrb.String(default = "glibc"),
67-
"module_name": lambda: attrb.String(),
68-
"py_limited_api": lambda: attrb.String(
69-
default = "",
70-
),
71-
"src": lambda: attrb.Label(
72-
mandatory = True,
73-
providers = [CcSharedLibraryInfo],
74-
doc = "The cc_shared_library target to wrap.",
75-
),
76-
}
80+
PY_EXTENSION_WRAPPER_ATTRS = dicts.add(
81+
COMMON_ATTRS,
82+
IMPORTS_ATTRS,
83+
{
84+
"libc": lambda: attrb.String(default = "glibc"),
85+
"module_name": lambda: attrb.String(),
86+
"py_limited_api": lambda: attrb.String(
87+
default = "",
88+
),
89+
"src": lambda: attrb.Label(
90+
mandatory = True,
91+
providers = [CcSharedLibraryInfo],
92+
doc = "The cc_shared_library target to wrap.",
93+
),
94+
},
95+
)
7796

7897
def create_py_extension_wrapper_rule_builder(**kwargs):
7998
"""Create a rule builder for the wrapper."""

‎tests/cc/py_extension/BUILD.bazel‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ py_extension(
5151
py_extension(
5252
# A python extension that dynamically links to another shared library
5353
name = "ext_shared",
54+
imports = ["."],
5455
dynamic_deps = [
5556
":add_one_shared",
5657
],
@@ -152,6 +153,21 @@ py_test(
152153
],
153154
)
154155

156+
#####
157+
158+
py_extension(
159+
name = "ext_pkg_test",
160+
srcs = ["ext_pkg_test.c"],
161+
)
162+
163+
py_test(
164+
name = "py_extension_pkg_test",
165+
srcs = ["py_extension_pkg_test.py"],
166+
deps = [
167+
":ext_pkg_test",
168+
],
169+
)
170+
155171
py_extension_analysis_test_suite(
156172
name = "py_extension_analysis_tests",
157173
)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#include <Python.h>
2+
3+
static PyObject* get_magic_number(PyObject* self, PyObject* args) {
4+
return PyLong_FromLong(42);
5+
}
6+
7+
static PyMethodDef ModuleMethods[] = {
8+
{"get_magic_number", get_magic_number, METH_NOARGS, "Returns 42."},
9+
{NULL, NULL, 0, NULL}
10+
};
11+
12+
static struct PyModuleDef ext_pkg_test_module = {
13+
PyModuleDef_HEAD_INIT,
14+
"ext_pkg_test",
15+
NULL,
16+
-1,
17+
ModuleMethods
18+
};
19+
20+
PyMODINIT_FUNC PyInit_ext_pkg_test(void) {
21+
return PyModule_Create(&ext_pkg_test_module);
22+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
3+
from tests.cc.py_extension import ext_pkg_test
4+
5+
6+
class PyExtensionPkgTest(unittest.TestCase):
7+
8+
def test_import_via_package(self):
9+
self.assertEqual(ext_pkg_test.get_magic_number(), 42)
10+
11+
def test_direct_import(self):
12+
with self.assertRaises(ModuleNotFoundError):
13+
import ext_pkg_test # buildifier: disable=g-import-not-at-top # noqa: F401
14+
15+
16+
if __name__ == "__main__":
17+
unittest.main()

0 commit comments

Comments
 (0)