Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 27 additions & 6 deletions extensions/pyo3/private/pyo3.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,19 @@ def _py_pyo3_library_impl(ctx):
is_windows = extension.basename.endswith(".dll")

# https://pyo3.rs/v0.26.0/building-and-distribution#manual-builds
ext = ctx.actions.declare_file("{}{}".format(
ctx.label.name,
".pyd" if is_windows else ".so",
))
# Determine the on-disk and logical Python module layout.
module_name = ctx.attr.module if ctx.attr.module else ctx.label.name

# Convert a dotted prefix (e.g. "foo.bar") into a path ("foo/bar").
if ctx.attr.module_prefix:
module_prefix_path = ctx.attr.module_prefix.replace(".", "/")
module_relpath = "{}/{}.{}".format(module_prefix_path, module_name, "pyd" if is_windows else "so")
stub_relpath = "{}/{}.pyi".format(module_prefix_path, module_name)
else:
module_relpath = "{}.{}".format(module_name, "pyd" if is_windows else "so")
stub_relpath = "{}.pyi".format(module_name)

ext = ctx.actions.declare_file(module_relpath)
ctx.actions.symlink(
output = ext,
target_file = extension,
Expand All @@ -99,10 +108,10 @@ def _py_pyo3_library_impl(ctx):

stub = None
if _stubs_enabled(ctx.attr.stubs, toolchain):
stub = ctx.actions.declare_file("{}.pyi".format(ctx.label.name))
stub = ctx.actions.declare_file(stub_relpath)

args = ctx.actions.args()
args.add(ctx.label.name, format = "--module_name=%s")
args.add(module_name, format = "--module_name=%s")
args.add(ext, format = "--module_path=%s")
args.add(stub, format = "--output=%s")
ctx.actions.run(
Expand Down Expand Up @@ -180,6 +189,12 @@ py_pyo3_library = rule(
"imports": attr.string_list(
doc = "List of import directories to be added to the `PYTHONPATH`.",
),
"module": attr.string(
doc = "The Python module name implemented by this extension.",
),
"module_prefix": attr.string(
doc = "A dotted Python package prefix for the module.",
),
"stubs": attr.int(
doc = "Whether or not to generate stubs. `-1` will default to the global config, `0` will never generate, and `1` will always generate stubs.",
default = -1,
Expand Down Expand Up @@ -218,6 +233,8 @@ def pyo3_extension(
stubs = None,
version = None,
compilation_mode = "opt",
module = None,
module_prefix = None,
**kwargs):
"""Define a PyO3 python extension module.

Expand Down Expand Up @@ -259,6 +276,8 @@ def pyo3_extension(
For more details see [rust_shared_library][rsl].
compilation_mode (str, optional): The [compilation_mode](https://bazel.build/reference/command-line-reference#flag--compilation_mode)
value to build the extension for. If set to `"current"`, the current configuration will be used.
module (str, optional): The Python module name implemented by this extension.
module_prefix (str, optional): A dotted Python package prefix for the module.
**kwargs (dict): Additional keyword arguments.
"""
tags = kwargs.pop("tags", [])
Expand Down Expand Up @@ -318,6 +337,8 @@ def pyo3_extension(
compilation_mode = compilation_mode,
stubs = stubs_int,
imports = imports,
module = module,
module_prefix = module_prefix,
tags = tags,
visibility = visibility,
**kwargs
Expand Down
17 changes: 17 additions & 0 deletions extensions/pyo3/test/module_prefix/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
load("@rules_python//python:defs.bzl", "py_test")
load("//:defs.bzl", "pyo3_extension")

pyo3_extension(
name = "module_prefix",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why add these attributes and not change the target name to foo/bar?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried that first, e.g. for string_sum:

pyo3_extension(
    name = "foo/string_sum",
    srcs = ["string_sum.rs"],
    edition = "2021",
)

Building that target yields this error:

Error in fail: Crate name 'foo/string_sum' contains invalid character(s): /

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There were several quirks with getting the names to line up (pymodule <-> output binary <-> crate name) + getting the outputs in the right directory so Python registers it as nested module rather than a top level module. Adding these (hopefully simple) knobs seemed like the cleanest approach.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm nervous about the amount of indirection this introduces. What is the use case here that directory structure can't be made to what you want?

Copy link

@ags-openai ags-openai Nov 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I follow w.r.t. indirection. This change tackles two related issues on how the native extension gets imported:

(1)

Per the pyo3 docs, the lib name must match the pymodule definition.

[lib]
# The name of the native library. This is the name which will be used in Python to import the
# library (i.e. `import string_sum`). If you change this, you must also change the name of the
# `#[pymodule]` in `src/lib.rs`.
name = "string_sum"

As it stands with rules_rust the target name was being used to determine the final extension file path. Imagine you have a python library "foo" that has regular python code + a private extension you want to import as "_foo_internal". You'd have to declare your extension as follows:

pyo3_extension(
    name = "_thing_internal",
    # ...
)

The underscore prefix on the bazel target implies that it's not a first class target in the build graph when this is definitely not the case. Related, build generators often want to follow nice patterns for generated targets. So imagine we generated <name>_pyo3_ext for all pyo3 extensions-- this would mean out python import path also has the same suffix. The current behavior is tolerable but somewhat quirky and undesirable.

(2)

As for the second issue, to get a rust extension importable/loadable at a full module path you need to place the lib in the nested directory structure. Roughly:

import foo.bar # ---> foo/libfoo.so
import foo.bar.baz # --> foo/bar/libbaz.so

The current rules don't give you control over the output path of the extension, so the best you could do is to manually move the file in a subsequent target. But injecting my own copy on top of these rules would nuke the python providers (and the stub generation) as they just assume a root module.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing I can think of to make the UX of this change a bit cleaner is to squash the two params into one, e.g. module = "foo.bar" and then the rules/macros can split accordingly.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By indirection I mean a developers ability to understand where a target came from. Seeing //:well_hello_there in as a bazel target and then in python code seeing the.rebel.alliance I think is going to lead to more confusion than it's worth for the alternate import path. What is the story for how folks are expected to understand where code is being defined?

Copy link

@ags-openai ags-openai Nov 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seeing //:well_hello_there in as a bazel target and then in python code seeing the.rebel.alliance

Sure, but that's a pretty egregious example I think. The naming is purposefully confusing and something folks can already do freely across most Bazel repos. Take rust_binary or any binary rule for that matter:

rust_binary(
   name = "well_hello_there",
   binary_name = "the.rebel.alliance.exe",
)

I don't want to configure my pyo3 extension targets in any purposefully confusing manner; I want to name them so the Bazel side is idiomatic for Bazel and the Python side is idiomatic for our Python usage.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't want to configure my pyo3 extension targets in any purposefully confusing manner; I want to name them so the Bazel side is idiomatic for Bazel and the Python side is idiomatic for our Python usage.

I'm not suggesting you're trying to do something malicious or anything haha. I've had a similar experience with pybind11 rules and it was incredibly frustrating where two different teams adopted two different naming conventions and debugging issues became harder for no meaningful reason. I opted to have them define a file with the name they wanted and reexport all symbols so there was a clear path to follow.

However, if this feature is strongly desired then I'd prefer there to just be module_name (matching the crate_name attribute) to be the fully qualified module name (combined prefix and name).

srcs = ["bar.rs"],
edition = "2021",
imports = ["."],
module = "bar",
module_prefix = "foo",
)

py_test(
name = "module_prefix_import_test",
srcs = ["module_prefix_import_test.py"],
deps = [":module_prefix"],
)
12 changes: 12 additions & 0 deletions extensions/pyo3/test/module_prefix/bar.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use pyo3::prelude::*;

#[pyfunction]
fn thing() -> PyResult<&'static str> {
Ok("hello from rust")
}

#[pymodule]
fn bar(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(thing, m)?)?;
Ok(())
}
19 changes: 19 additions & 0 deletions extensions/pyo3/test/module_prefix/module_prefix_import_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Tests that a pyo3 extension can be imported via a module prefix."""

import unittest

import foo.bar # type: ignore


class ModulePrefixImportTest(unittest.TestCase):
"""Test Class."""

def test_import_and_call(self) -> None:
"""Test that a pyo3 extension can be imported via a module prefix."""

result = foo.bar.thing()
self.assertEqual("hello from rust", result)


if __name__ == "__main__":
unittest.main()