PyO3 Crates
PyO3 is the standard Rust library for writing Python extension modules. A large part of the Rust ecosystem that is interesting from a scientific-computing point of view is published this way: a Rust crate whose functions and types are annotated for Python and shipped as a Python package.
RustCall can bind such a crate to Julia without changing it. The crate's author does not have to know about RustCall, and you do not have to fork the crate and add #[julia] to it.
Read this page when the Rust crate you want to call was written for Python with PyO3, or when you maintain one Rust crate that should serve both Python and Julia. For a crate you write for Julia alone, use #[julia] and External Crate Bindings; nothing here is needed.
Most of this page is reference material for the cases where a build or a binding is refused. The first three sections are what you need to get started.
PyO3 in a minute, for Julia users
A PyO3 crate marks what it exposes with attributes, in the same way RustCall's #[julia] does:
use pyo3::prelude::*;
#[pyfunction]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[pyclass]
pub struct Point {
#[pyo3(get, set)]
pub x: f64,
#[pyo3(get, set)]
pub y: f64,
}
#[pymethods]
impl Point {
#[new]
pub fn new(x: f64, y: f64) -> Self {
Point { x, y }
}
pub fn norm(&self) -> f64 {
(self.x * self.x + self.y * self.y).sqrt()
}
}| PyO3 | Means | What RustCall binds it as |
|---|---|---|
#[pyfunction] | a function exposed to Python | a Julia function |
#[pyclass] | a struct exposed as a Python class | a Julia type holding a handle |
#[pymethods] impl | the class's methods | Julia functions taking the object first |
#[new] | the method Python calls as the constructor | the Julia constructor, Point(3.0, 4.0) |
#[staticmethod] | a method without self | a static method |
#[pyo3(get, set)], #[getter], #[setter] | Python attributes | Julia properties, p.x and p.x = … |
PyResult<T> | Result<T, PyErr>: a value or a Python exception | RustCall.RustResult{T, String} |
#[pymodule] | the function that registers everything into a Python module | used by the Python host path to find the items |
Two ways to bind a PyO3 crate
There are two, and they suit different crates.
| Native wrapper (the default) | Python host (pyo3_host=true) | |
|---|---|---|
| How it works | RustCall generates a second crate that calls the PyO3 crate's items as ordinary Rust and exports them through the C ABI | The crate is built as the Python extension it already is, imported with PythonCall, and called through Python |
| Python at run time | no interpreter is started | yes, PythonCall's interpreter |
Needs using PythonCall | no | yes |
| Which items are reachable | pub items whose signatures do not involve Python objects | everything the crate's #[pymodule] registers, including private items and ones taking Python<'_>, numpy arrays or Python callables |
PyResult error text | one fixed sentence (there is no interpreter to render the Python exception) | the Python exception's own message |
| Object lifetime | Julia's finalizer drops the Rust value | owned by Python |
| Choose it when | the crate's API is plain Rust underneath: numbers, strings, its own structs | the crate is a "real" Python extension, written in terms of Python objects |
If you are unsure, try the native wrapper first and look at what RustCall.scan_report(crate_path) says it can and cannot wrap. If the items you need are listed as not_public or pyo3_type, use the Python host.
The native wrapper
using RustCall
Sample = @rust_crate "path/to/pyo3_crate"
Sample.add(2, 3) # => 5
p = Sample.Point(3.0, 4.0)
Sample.norm(p) # => 5.0
p.x # => 3.0What the machine needs depends on how the crate depends on pyo3:
- If pyo3 is an optional dependency behind a Cargo feature and you build without that feature (
default_features=false, or simply not listing it), the wrapper is plain Rust and no Python installation is involved at all. - If pyo3 is a mandatory dependency, the wrapper library has to link against libpython, so the build needs a Python installation that ships a linkable library (on Linux, the
python3-devpackage or a conda Python). SetPYO3_PYTHONto choose the interpreter. No interpreter is started; the library is only linked. - If the selected features include pyo3's
extension-module, the crate can only be loaded by Python. The native wrapper refuses, and the Python host is the way in.
The link plan explains how RustCall decides between these and what to do when it refuses.
The Python host
using RustCall
using PythonCall
Sample = @rust_crate "path/to/pyo3_crate" pyo3_host=true
Sample.add(2, 3)
Sample.Point(3.0, 4.0).xThe Python host path below describes it in full.
One crate for both languages
When you write the crate yourself, put #[julia] beside the PyO3 attributes on the same definition. #[julia] leaves the item as written, so both attributes apply:
#[julia]
#[cfg_attr(feature = "python", pyo3::pyfunction)]
fn add(a: i32, b: i32) -> i32 {
a + b
}#[cfg_attr(feature = "python", …)] applies the PyO3 attribute only when the crate's python feature is enabled. With pyo3 declared as an optional dependency behind that feature, the Julia build never mentions Python, and the Python build (maturin build --features python) sees the same function. Julia calls it through RustCall's own wrapper, with everything #[julia] supports. The repository's examples/SampleCratePyO3.jl is a complete package built this way.
Where to find what on this page
- The Python host path: the interpreter-backed binding in detail.
- Using it: the native wrapper in detail, including feature selection and what is not wrapped.
- Scanning a crate and What the manifest records: how RustCall reads a PyO3 crate, for diagnosing a missing binding.
- The link plan: when and how a wrapper links libpython.
- Making pyo3 optional: the crate layout that needs no Python on the Julia side.
Internally the native wrapper is built in three steps, which the sections below refer to by name. The scan (RustCall.scan_report) lists every PyO3 item the crate declares, which of them a wrapper can call, and why the others cannot be. The link plan (RustCall.pyo3_link_plan) decides from the crate's Cargo.toml whether a wrapper library can be linked and loaded, and with which flags. The wrapper crate is what @rust_crate and RustCall.write_bindings_to_file then generate, build under that plan, and bind. Older text on this page calls these Phase 1, Phase 1.5 and Phase 2.
The Python host path
Everything from "Using it" down binds a PyO3 crate from outside: a generated wrapper crate calls the target's pub, interpreter-free items through a C ABI and links libpython. That is the opposite of how a real PyO3 crate is written — #[pyfunction]/#[pyclass] need no pub, and real APIs are written in terms of Python<'_>, Py<T>, numpy arrays and Python callables — so the scan reports not_public (rustc E0603) and pyo3_type:<T> for exactly the items the crate intends to expose.
pyo3_host=true (#424) binds such a crate as-is. It builds the crate as the Python extension it already is — the extension-module build the link plan calls :unlinkable, which is the right build when CPython is the one that loads it — imports it through PythonCall, and calls the imported module:
using RustCall
using PythonCall # enables the RustCallPyO3HostExt package extension
Sample = @rust_crate "path/to/pyo3_crate" pyo3_host=true
Sample.add(Int32(2), Int32(3))
Sample.Point(3.0, 4.0).xWhat changes:
- No
pubis needed, and no wrapper crate is generated. PyO3 registered the item inside the crate, so importing reaches it; a Rust path is never taken. Python<'_>,Py<T>, numpy and callables are ordinary. The value bridge, the GIL and object lifetime are PythonCall's.PyResult<T>carries the real message. It is stillRustResult{T, String}, but theErrpayload is the exception's own text — the C-ABI path'sPYO3_OPAQUE_ERRORexists only because it has no interpreter to render aPyErrwith.- Fields go through the Python object.
#[pyo3(get, set)]installs the descriptor inside the crate, so a private field of a private struct works. - Python owns lifetime. There is no generated
<Class>_freeand nofinalize. - The crate is built lazily, on the first call: pyo3's build is pinned with
PYO3_PYTHON = PythonCall.python_executable_path(), and a Python interpreter may not be started during precompilation. The crate's sources and that interpreter are part of the artifact cache key. What the first call costs, and how to pay part of it earlier, is under "The first call" below.
Three examples use it, and one shows why it exists:
Sample = @rust_crate "examples/SampleCratePyO3Only.jl/deps/sample_crate_pyo3_only" \
submodule="Bindings" pyo3_host=trueThe crate there has no pub on any item and is crate-type = ["cdylib"] with pyo3's extension-module; examples/RustCrateMacroPyO3Only.jl binds the same shape, and examples/SampleCratePyO3.jl carries #[julia] and PyO3 attributes on one definition (also with no pub). The older C-ABI path remains for the crate that is pub and interpreter-free, and for the cases where a wrapper crate's runtime guarantees (panic containment, generation/liveness, RustResult for a PyResult with no Python around) are wanted.
A crate that is not cdylib is no obstacle — the build selects cdylib explicitly — but it must have a #[pymodule]: that initializer is what is imported, and only what it registers is reachable. That includes a declarative module (#[pymodule] mod name { ... }, PyO3's own shape): the bindings follow the declarative nesting, so a direct item is Sample.f and one in a nested #[pymodule] mod inner is Sample.inner.g.
The host path converts every value by what it is at run time, never by the Rust spelling of its position, so the shapes a PyO3 crate actually uses — aliases, re-exports and a crate's own types included — are handled rather than reported as skips. Arguments are untyped; Python checks them as it would a Python caller's.
- Classes. A Julia class handle is passed as the Python object it holds, and a returned object whose Python type is one of the module's classes is that class's Julia handle — through
Py<T>,Py<Self>, an alias, anOptionor aVecalike. PythonNoneisnothingboth ways. - numpy arrays. A Julia array of numbers is passed as a
numpy.ndarraywhen numpy imports, because pyo3-numpy extracts from nothing else; PyO3 reads aVecfrom it as from any sequence. A numpy return is converted back to a JuliaArray. - Return types. The extractor's hint for a return (a primitive,
String, aVec, a numpy array) types what the value conversion left; a value that does not fit it stays a Python object. - Python callables. A Julia function passed as an argument arrives as a Python callable (PythonCall wraps it), and a
Py<PyAny>argument or return stays a Python object. #[classmethod]. Python's bound descriptor passes the class, so the binding drops that argument from the Julia signature and calls through the class object.#[pyo3(pass_module)]is the same: the injected module is not a Julia argument.- Field direction. A get-only
#[pyo3(get)]field is readable and not assignable;setproperty!raises a JuliaArgumentErrornaming it. - Properties. An exposed field and the
#[getter]/#[setter]methods of one Python attribute are one property, underjulia_binding_nameof the attribute PyO3 exposes (#524):#[getter] fn r#forwith#[setter] fn set_forisobj.for_, readable and writable;#[getter(end)]isobj.end_;#[getter] fn get_xisobj.x. Two attributes one Julia name would read (forand a fieldfor_) are refused. async fnis refused. The host path has no event loop to drive the coroutine, so the extractor'sasync_fnrefusal is honoured and no binding is emitted, rather than handing Julia an awaitable that never runs.
PyResult<T> remains RustResult{T, String} on this path too; the Err payload is the interpreter's own message, so a caller keeps one error surface whether the crate was bound from outside or imported as the extension it is.
The first call, and paying it earlier (#449)
The first host call in a session — RustCall.pyo3_host_import(crate), or the first call of a binding @rust_crate ... pyo3_host=true generated — scans the crate, computes its cache key, finds (or builds) the extension module and imports it. With the artifact already cached that is a few subprocesses (the extractor, the toolchain probes, cargo tree, one start of the interpreter for its EXT_SUFFIX and fingerprint) and no compilation of RustCall's code: RustCall's own package image carries the scan and the cache lookup (src/macros/precompile.jl runs that interpreter-free half against a throwaway crate while RustCall precompiles), and RustCallPyO3HostExt's image carries the import. A downstream package needs no precompile directive of its own for it. Before #449 the same first call spent most of a second compiling RustCall's scan and cache code, and nothing downstream could bake it: the path is reached through dynamic dispatch, so Base.precompile stopped at the thin method, and executing it during precompilation needs an interpreter.
The two halves are separately callable when the remaining cost should move elsewhere:
# interpreter-free: scan, key, the cached artifact — or the build. Python runs
# only as a subprocess, for the module suffix and the interpreter fingerprint.
artifact = RustCall.build_pyo3_extension(crate; python = PythonCall.python_executable_path())
# needs the interpreter: put the artifact's directory on `sys.path` and import.
mod = RustCall.pyo3_host_import(artifact)pyo3_host_import(crate) is exactly those two calls. Where the build runs decides what the first call has left to do:
- In the package's
__init__(PythonCall's own__init__has run by then, so its interpreter is known): keep the returnedPyO3Extensionin aRef-like slot and the first call ispyo3_host_import(artifact)— the interpreter check and the import, nothing else. Loading the package then pays the scan, the probes and, the first time, the Cargo build. - In a
deps/build.jl: that is another process, so itsPyO3Extensiondoes not survive into the runtime, and there is no metadata to rebuild it from. What it does is warm the cache: the runtime'spyo3_host_import(crate)then finds the artifact and pays the scan, the probes and the lookup — well under a second, with no compilation — but not the Cargo build, which is the cost worth moving.
Neither may run while the package precompiles: the artifact is keyed by the interpreter, and the one PythonCall will use is not known until it initialises.
The artifact must be the one for the interpreter PythonCall runs: pyo3 links against that interpreter, and CPython ignores an extension whose file tag is another version's. pyo3_host_import(artifact) therefore checks the artifact's interpreter fingerprint (implementation, version, SOABI, library, machine architecture) and EXT_SUFFIX against those of PythonCall.python_executable_path() before importing — one interpreter start — and raises a RustError naming both on a mismatch. The path alone decides nothing: an interpreter upgraded in place keeps its path and changes its ABI, and a virtual environment's launcher and its base are one interpreter under two paths. The one-argument pyo3_host_import(crate) skips the check, having just built for this interpreter. A deps/build.jl should build with the interpreter PythonCall will use (the one CondaPkg resolves, or JULIA_PYTHONCALL_EXE), not one of its own choosing.
Which pyo3 versions work
Most of what RustCall generates for a PyO3 crate calls the crate's own functions and works on any pyo3 the crate itself builds against.
Two shapes are different, because their wrappers have to reach Python themselves — a defaulted callable (#[pyo3(signature = (x = 1))]) and a class made Python-owned by inheritance (#[pyclass(extends = ...)]). Those are emitted with Python::initialize and Python::attach, which arrived in pyo3 0.26; 0.25 and earlier spell the same operations pyo3::prepare_freethreaded_python and Python::with_gil. A crate on an older pyo3 is refused before the wrapper is built, naming the version it resolved and the floor, rather than failing later with rustc errors about generated code you never wrote.
RustCall also aliases the crate's own pyo3 as rustcall_pyo3 for those wrappers, and names the package Cargo resolved — by exact version for a registry release, by directory for a path dependency, and by resolved commit for a git one. That matters: two pyo3 instances in one build do not merely duplicate work, they produce a dispatcher whose Python and traits come from a different crate instance than the types in your macro metadata, and nothing using the dispatcher compiles.
The wrapper spends two crate names on itself — rustcall_pyo3 and rustcall_julia_macros, the runtime its quiet-panic guard comes from. Nothing reserves a crate name, so if your crate is called either of those, the wrapper depends on it under rustcall_target_<name> (a plain Cargo rename, package = "<your name>") and the generated Rust names it that way too. You do not have to do anything; it is only worth knowing if you read the generated Cargo.toml.
Using it
using RustCall
# a crate written for PyO3 only; this one is RustCall's test fixture
Sample = @rust_crate "test/fixtures/sample_crate_pyo3_only"
Sample.add(Int32(2), Int32(3)) # 5
Sample.shout("hello") # "HELLO!"
Sample.parse("42") # RustResult{Int32, String}(true, 42)
Sample.render(true) # RustResult{String, String}
Sample.defaulted() # 37, from a private Rust default helper
p = Sample.Point(3.0, 4.0) # #[new]
Sample.norm(p) # 5.0
p.x # 3.0, through #[pyo3(get, set)]
p.x = 6.0
Sample.label(p) # a String method
Sample.scaled(p, 2.0) # a PyResult method
Sample.shifted(p, 1.0) # RustResult{Point, String}
c = Sample.InheritedCounter() # #[pyclass(extends = BaseCounter)]
Sample.increment(c) # defaulted mutating methodNothing in the crate changes. RustCall generates a second crate that depends on it and exports one extern "C" entry point per wrappable item:
- a free
#[pyfunction]becomesrustcall_<name>; - a
#[pyclass]becomes an opaque handle with a<Class>_freedestructor,rustcall_<Class>_<method>for every method of every#[pymethods]block (#[new],#[staticmethod],#[getter],#[setter]included), andrustcall_<Class>_get_<field>/_set_<field>for the fields#[pyo3(get, set)],get_allorset_allexpose.
Public String fields support both reads and writes, including a #[pyo3(set)] write-only field. Setters take a UTF-8 byte pointer and length, so empty strings and embedded NUL characters are preserved; Julia rejects invalid UTF-8 before entering Rust. Inline bindings expose set_<field>! alongside property assignment; written bindings expose property assignment. Private fields and setters on a frozen class remain inaccessible through this native wrapper path.
Public Vec<T> fields are also readable and writable when T has a concrete scalar or pointer FFI representation (i8–i64, u8–u64, isize, usize, f32, f64, and raw pointers). A getter clones the Rust vector and returns a RustVec{T}; call collect to copy it into a Julia Vector, and drop! it when deterministic release matters. The object retains the exact release function and library generation that allocated the buffer, including across reloads. Setters accept Julia iterables and convert every element to T before entering Rust. Vec<bool> is excluded because Rust bit-packs it; nested vectors and elements without a concrete Julia FFI layout are excluded.
A crate may carry both kinds of marker. #[julia] is additive since #279 and exports rustcall_<name> from the crate itself, so the wrapper generates entry points for the PyO3 items and links the #[julia] ones; one @rust_crate module exposes both. An item marked both ways belongs to #[julia], which already owns that symbol. test/fixtures/sample_crate_pyo3_mixed is that shape — and its [lib] name deliberately differs from its package name, because Rust code names a dependency by its library target, which is what the generated calls use.
Every one of those comes out of rustcall_julia_core::codegen::generate_wrapper — the same generator #[julia] goes through since #279 — so the (ptr, len) string ABI, the CResult / COption aggregates and the per-wrapper panic channel are identical to a #[julia] crate's, and the Julia side binds both with the same emitters. A panic inside a wrapped item is caught and raised as RustCall.RustPanicError, not an abort.
Selecting a feature set
The wrapper is built against one feature set of the target crate, named the way Cargo names one:
Sample = @rust_crate "path/to/crate" features=["python"] default_features=falseRustCall.pyo3_feature_candidates says which features activate pyo3 and which of those also pull extension-module; see Choosing a feature set below. The feature set is part of the artifact identity, so two builds of one crate under different features are two different cached libraries and two different registry entries — as is the build environment the wrapper inherits (RUSTFLAGS and the rest of the #282 allowlist), which reaches cargo and so decides the binary.
That environment is read once per build. The link plan, the interpreter selection, the cfg probe, the key, the wrapper build and the module's record all come from one snapshot taken when @rust_crate (or write_bindings_to_file, or RustCall.build_pyo3_extension on the host path) starts. A PATH or PYO3_PYTHON changed by another task during the build selects no other interpreter. The interpreter the build is pinned to is asked again after the build. If it was replaced in place, for example upgraded under the same path, the build is refused before it is cached, because the library was configured for a Python its key does not name.
The crate needs an rlib target
The wrapper crate depends on yours as a Rust library, so your [lib] must offer a target a dependent can link: no crate-type at all (Cargo's default is an rlib), or a list containing "rlib" (or "lib" / "dylib"). A PyO3 extension crate is often
[lib]
crate-type = ["cdylib"]alone — Cargo then warns that the dependency "provides no linkable target" and the generated wrapper fails to compile. RustCall refuses such a crate before building anything, with the fix in the message:
[lib]
crate-type = ["cdylib", "rlib"]The extra target changes nothing about the Python extension module; it only lets other Rust code — the wrapper — link the crate.
What is not wrapped, and why
The scan refuses what a wrapper crate could not name (a non-pub item, a signature mentioning a type that needs a live interpreter, a generic, a #[pymodule]) or could not call (an async fn, async_fn: a wrapper would return the future rather than the value it resolves to, and has no executor to drive it), and what the Julia module could not hold (julia_name_collision): a class is a Julia type and its constructor, so a free function or static method with a class's name would redefine it; and a #[staticmethod] is bound as a module-level Julia function named after the method, like a #[pyfunction], so a second class with a parse(s) of its own — or a class parse(s) next to a free parse(s) — would silently replace the first definition. Classes keep their names, then free functions, then static methods in manifest order; the later item is refused and the reason names the earlier one. The generator then refuses what it could not lower:
| reason | meaning |
|---|---|
unsupported_arg:<T> | an argument that is neither FFI-compatible nor a String / &str |
unsupported_return:<T> | a return value that does not cross the C ABI as a single value (a Vec, a struct by value, a Result payload that is one of those) |
py_result_payload:<T> | a PyResult whose Ok type cannot be lowered into the CResult aggregate, such as PyResult<Vec<_>> or an unrelated struct by value. Widening this is tracked in #303 |
unsupported_return:Result<…> on a method | this wrapper crate lowers a plain Result / Option into a CResult / COption for a free function only. A #[julia] method does lower one too since #268, through RustCall._method_payload_plan, but that Julia-side emitter is keyed to a #[julia]-attributed method and never runs for a #[pymethods] one scanned here; emitting the aggregate anyway would be worse than not wrapping the method. #303 owns widening the PyO3 wrapper path to match |
cfg_undecided:<predicate> | the item is behind a #[cfg] the scan could not decide, so whether the build the wrapper links against has it is unknown. Only reachable when Cargo could not resolve the build (plan.resolved == false) |
scan_report prints both lists, and the second one with the symbol each wrapped item is exported under:
RustCall.scan_report("test/fixtures/sample_crate_pyo3_only")Nothing is guessed: an item that is not listed under "Wrapper crate exports" has no symbol, and no Julia definition is generated for it.
PyResult<T>: an opaque error, on purpose
A PyResult<T> becomes a Julia RustResult{T, String}. Scalar payloads cross by value, String / &str success payloads use an owned buffer released after Julia copies it, and a method returning PyResult<Self> boxes the new class value and retains the destructor and liveness flag from the same library generation. On the Err side the value is always the same sentence:
RustCall.PYO3_OPAQUE_ERROR
# "PyErr (Python-side error; message unavailable without an interpreter)"The CResult_<owner> mirror the Julia side declares for that aggregate subtypes RustCall.FFIByValue — RustCall's own layout assertion about a #[repr(C)] type it generated itself (#245), the same one the #[julia] path makes about its CResult_* mirrors. Returning an aggregate by value without such an assertion is refused since #295.
That is not laziness. Creating and dropping a PyErr without a Python interpreter is safe, but rendering one is not: Display/Debug on a PyErr asserts inside pyo3 that the interpreter is initialized, and the resulting panic crossing extern "C" aborts the process. Reading only the exception type would need a Python token, which a wrapper crate by definition does not have. So the generated code drops the PyErr without ever looking at it and reports a fixed code, and Julia turns that into the sentence above. A PyResult<()> reports success or failure the same way, with nothing as its Ok value.
The wrapper is generated for one build, and scanned under it
The scan that feeds the generator runs under the configuration the wrapper is compiled with, whenever Cargo could answer (plan.resolved). So an item behind a #[cfg] is decided, not refused: asking for features = ["python"] and then declaring every feature-gated item undecidable would refuse exactly the API that was requested.
Only an unresolved plan — no Cargo, an offline registry, a crate that does not resolve — falls back to lenient evaluation, and there a #[cfg]-carrying item is refused with cfg_undecided rather than compiled into a call to something the build may not have.
One consequence is worth stating plainly, because it decides what :python_free is good for. A crate that makes pyo3 optional writes its markers as #[cfg_attr(feature = "python", pyfunction)]; with the feature off, that marker is not applied, so the build has no Python API and there is nothing for a wrapper crate to export. @rust_crate says so and falls back to binding the crate the way it did before #275, rather than building an empty cdylib. Turn the feature on and the same crate is wrapped in full — as a :link_libpython build, because activating pyo3 is what puts it in the graph.
:python_free therefore means "this build has no pyo3, and so no PyO3 items"; it is an answer the plan gives, not a mode in which wrappers get built. test/fixtures/sample_crate_pyo3_optional demonstrates both halves.
Scanning a crate
using RustCall
RustCall.scan_report("test/fixtures/sample_crate_pyo3_only")Crate sample_crate_pyo3_only v0.1.0 (…/test/fixtures/sample_crate_pyo3_only)
Build scanned: default features
RustCall items (wrapped today): 0
PyO3 items the scan can name: 13
fn add -> i32 [py_function]
fn shout -> String [py_function]
fn parse -> PyResult<i32> [py_function]
struct Point [py_class]
method new -> Self
method norm -> f64
method origin -> Self
method sum -> f64
…
Wrapper crate exports: 13
fn add -> i32 [py_function] -> rustcall_add
struct Point [py_class] -> Point_free
method new -> Self -> rustcall_Point_new
…
PyO3 items skipped: 3
fn private_add -> i32 [py_function] — not `pub`, so a wrapper crate cannot name it (rustc E0603)
fn describe -> i32 [py_function] — the signature uses a type that needs a live Python interpreter (Python<'_>)
fn sample_crate_pyo3_only -> PyResult<()> [py_module] — a `#[pymodule]` initializer: it only means something to Python's import machinery
Link plan: link_libpython — pyo3 is a mandatory dependency, so the wrapper cdylib links libpython; … is added as an rpath at wrapper-build timeBy default scan_report resolves the build with Cargo — pyo3_link_plan runs cargo tree and a wrapper-shaped cfg probe — so the items behind #[cfg] are decided for the build the wrapper is compiled with. For a probe-free Phase 1 that runs no Cargo at all, pass resolve = false: the plan is the declaration-only reading of Cargo.toml, plan.resolved is false, and the scan is lenient, so a #[cfg]-carrying item is reported as undecided rather than decided away. That is the mode for large crates (the cfg probe compiles the crate's whole dependency graph as a wrapper dependency, which can be minutes and gigabytes), offline machines, and item inventories that need no link plan. generate = false is orthogonal: it skips the Phase-2 generator, but the default plan resolution still runs.
RustCall.scan_crate returns the same information programmatically, in the pyo3_functions and pyo3_structs fields of the CrateInfo. Its default lenient scan still invokes Cargo — _cfg_snapshot(:lenient) runs the dependency-free cargo rustc --release --lib -- --print cfg probe for target predicates, and an inherited edition / version can fall back to cargo metadata — so for a run that touches no Cargo use scan_report(...; resolve = false), or pass an explicit empty cfg_text to scan_crate. Generating the wrapper's lib.rs — which is what the "Wrapper crate exports" column reports — compiles nothing either.
What the manifest records
Manifest schema 5 adds, for every function, struct and method:
| column | meaning |
|---|---|
attribute | the origin of the entry: julia for a RustCall attribute, py_function / py_class / py_methods / py_module for the PyO3 scan. On a method it is the attribute of the impl block the method came from (julia, py_methods; omitted for an inline-mode impl), which need not be the struct's own |
vis | visibility as written: pub, pub(crate), pub(super), pub(in path), or empty for a private item |
skip_reason | why the item cannot be wrapped, empty when it can |
python_name | the name PyO3 exposes it under, when it is not the Rust name as written: #[pyo3(name = "...")], a raw r#for as for, and for a #[getter] / #[setter] method the property (#[getter(x)], or the name without a get_ / set_ prefix) |
accessor | getter / setter for a #[getter] / #[setter] method |
argument / field py_shape, function / method py_return | a hint for the Python-host bindings, read off the type's spelling with no path resolution: vec / option (bare or under a std root, with an inner hint), array (pyo3-numpy, with rank and element name), scalar, string, unit, injected (Python<'_>, a pass_module module) or opaque. The host converts values by what they are at run time; the hint only types what that left, and says which arguments the interpreter supplies |
return_kind + ok_type / err_type / inner_type | on methods too, not just free functions: a #[pymethods] method returning PyResult<T> is py_result with T, so Phase 2 never re-reads the Rust type spelling |
field abi = "vec" + vec_element + free_symbol | schema 10's owned-vector contract: the exact Julia element layout and the export that must release this getter's (ptr, len, cap) buffer |
argument python_default + python_kind | schema 12's PyO3 call shape; defaults remain Rust expressions and are evaluated only by PyO3's original dispatcher |
struct pyo3_extends + pyo3_options | schema 12's Python object shape, used to select a Python-owned inheritance handle |
struct python_owned_handle | schema 13's authoritative wrapper decision; retained after unsupported methods are filtered so generated modules still pin the image and keep finalizers live |
A scanned item's symbol is the wrapper a Phase-2 wrapper crate will export — rustcall_<name> for a function, rustcall_<Struct>_<method> for a method, the same scheme #[julia] uses since #279 — and exported is false, because nothing emits it yet. The manifest describes what Phase 2 will generate.
Skip reasons
| reason | meaning |
|---|---|
not_public | no externally accessible Rust path names the item. A pub item inside a private module can be wrapped when an accessible pub use re-exports it. Restricted or private imports do not grant access. |
pyo3_type:<T> | the signature mentions <T>, which only exists with a live interpreter: PyObject, Py<T>, Bound<'_, T>, &PyAny, Python<'_>, PyRef, PyRefMut, anything under pyo3:: |
pymodule | a #[pymodule] initializer: it exists to be called by Python's import machinery |
generic | a generic item; monomorphizing PyO3 items is out of scope |
owner_skipped:<reason> | a method whose #[pyclass] is itself skipped for <reason> |
symbol_collision:<owner> | another item already claims the symbol this one would get. Symbols carry the module path since #300 (a::run → rustcall_a__run), so two pub fn run in different modules no longer meet; what remains is a same-module coincidence — an item whose own name spells another item's generated symbol, such as a #[pyfunction] fn P_get_v next to a #[pyclass] P with a v getter |
not_public is the reason you will see most often, and it is worth knowing why: pyo3 does not require pub anywhere. #[pyfunction] fn add(...) and a #[pymethods] block full of fns without pub work perfectly for Python, because pyo3 generates the wrapper inside the crate. A RustCall wrapper crate is compiled outside it and hits E0603, which is a compile error, not something to work around — so the scan reports those items rather than dropping them, and adding pub in the target crate is the fix.
PyResult<T> is wrapped, not skipped
PyResult<T> is recorded as return kind py_result with the Ok type in ok_type, and is not a skip reason. Creating and dropping a PyErr without an interpreter is safe; only rendering one is not — Display/Debug on a PyErr panics inside pyo3, and a panic crossing extern "C" aborts the process. Phase 2 therefore lowers it to an opaque error flag, and generated code must never format a PyErr.
#[pyclass] structs are opaque handles
RustCall does not depend on a #[pyclass] having #[repr(C)]. A plain class uses the fast native path: its wrapper boxes the Rust value and accesses it through Rust-generated accessors. A class with extends, or whose methods use PyO3 defaults, instead uses a Python-owned opaque handle. That distinction is manifest data; Julia still sees only Ptr{Cvoid}. Fields are exposed only when pyo3 exposes them — #[pyo3(get)], #[pyo3(set)] or both, or get_all / set_all on the class — each accessor on its own, so a set-only field is a setter with no getter (obj.field = v works, obj.field is a missing field) — and only when they are pub: pyo3 generates its descriptor inside the crate, so #[pyo3(get)] works on a private field, but a wrapper crate compiled outside cannot read Struct::field. A private one is still listed, with no getter and no setter. Methods are collected from every #[pymethods] block for the type: #[new] becomes the constructor, #[staticmethod] and #[classmethod] are static, #[getter] / #[setter] are accessors. (A #[classmethod] takes a &Bound<'_, PyType> first argument, so it is normally skipped for using a pyo3 type.)
subclass, dict, and weakref affect the Python object, not a plain native handle. extends does affect ownership: PyO3 constructors return an initializer containing both child and base state, so RustCall constructs the registered Python type and retains its Py<PyAny> instead of flattening the result into a Box<Child>. Calls and field access attach to Python and operate on that same object. Finalizers only publish a preallocated node to a lock-free queue; a background Python-attached safe point performs the actual decref. The wrapper image is process-pinned because PyO3's registered type and that safe point keep callbacks into it after a logical RustCall unload.
Every call the wrapper attaches to Python from Julia first tells CPython which stack it is on (#542). A Julia task runs on a stack of its own, and CPython 3.14 judges "close to the stack limit" against the OS thread's stack: on a task stack it always says yes, defers the deallocation of every container it frees to a list that is never drained there, and whatever those containers referenced — the self of a dispatched method call — is never released, so a Python-owned object's Rust Drop never runs. The attached closure reads the current task's stack bounds from Julia (jl_active_task_stack) and passes them to PyUnstable_ThreadState_SetStackProtection (CPython 3.14.1 and later). The range starts 64 KiB above the bottom Julia reports, clear of the guard region Julia puts at the bottom of a task stack, so that CPython's limit lies on usable stack and deep recursion in C raises RecursionError (#546). Before it detaches the closure puts back what the thread had: the bounds of the wrapper call it is nested in, if any (a wrapper call whose Python code calls Julia, which calls a wrapper again), or the thread's own bounds (PyUnstable_ThreadState_ResetStackProtection), so nothing else that enters Python on that thread (PythonCall, for example) inherits a task's stack (#547). These functions are looked up at run time. Python before 3.14 limits recursion by call count, not by address, and is unaffected. On Linux and macOS with CPython 3.14.1 or later this is complete. Two configurations are not covered, and a Python-owned object used from a task there may not be dropped until the process exits: CPython 3.14.0, which lacks the function, and Windows with CPython 3.14 or later, where the lookup is not implemented yet (#548).
PyO3 defaults keep their original Rust scope
For #[pyo3(signature = (...))] (including the signature nested in #[pyfunction(...)]) and legacy #[args(...)], the manifest records parameter kinds and default expressions. The expressions are descriptive only: Julia never evaluates or copies them. For every callable trailing-default arity the generated wrapper calls PyO3's original dispatcher, which evaluates a default where the macro generated it. A default may therefore call a private helper, and a defaulted mutating method updates the original Python-owned object. Keyword-only parameters supplied through RustCall's positional Julia surface are moved into Python keyword arguments by that dispatcher bridge.
Likewise, #[pyclass(generic)] enables Python generic aliases; it does not add Rust type parameters. The fixture exercises this valid form. PyO3 0.29 rejects #[pyclass] struct C<T> and #[pymethods] impl Trait for C before a wrapper can be built; tests check the actual compiler diagnostics. Expose trait behavior through an inherent #[pymethods] method that delegates to the trait instead; the fixture's Point::norm uses this pattern. Ordinary Rust generic internals can be hidden behind a concrete, non-generic #[pyclass].
Modules are followed, not guessed
An item's module_path records its canonical definition location, which fixes its exported symbol identity and Julia module layout. Schema 9 adds callable_path for an external Rust spelling when a public re-export is needed; an empty path uses module_path plus the item's name. The extractor therefore follows the crate's module tree from src/lib.rs (rustcall-extract manifest --crate-root) rather than treating each .rs file as its own root: pub mod api; backed by src/api.rs, src/deep/mod.rs, #[path = "..."] overrides, and an out-of-line module declared inside an inline one (mod outer { pub mod child; } → src/outer/child.rs) are all resolved the way rustc resolves them. A private parent blocks direct access, but an accessible pub use hidden::Item as PublicItem can provide the external call path. Named, chained and glob re-exports, including aliases of public modules, are resolved separately from local imports used to attach impl blocks. Private or restricted imports, inaccessible intermediate modules and ambiguous glob names do not grant external access. Conditional routes retain their cfg; an unconditional public route is preferred over a conditional alias.
Aliases do not create duplicate Julia owning types: the class is still bound once at its canonical Julia module location, while its constructor, methods and destructor call the accessible Rust spelling. Public reachability does not remove other restrictions such as async or unsupported signatures.
The root is the crate's library root: [lib] path when the manifest sets one, otherwise src/lib.rs. A mod declaration whose file does not exist (behind a pruned #[cfg], or generated at build time) is skipped rather than failing the scan.
Sources generated by Cargo build scripts
The resolved PyO3 scan runs the target's build script through Cargo before following generated includes. It uses that target package's OUT_DIR and cargo:rustc-env values, not a dependency's build environment or an ambient OUT_DIR from Julia's process. For example, a crate can expose its entire API through include!(concat!(env!("OUT_DIR"), "/api.rs")), even when its committed sources contain no PyO3 markers. Custom [package] build paths are honored by Cargo; build = false does not trigger build-script discovery.
Include paths support string literals, nested concat! of strings, and env! names present in the explicit build context. This is not arbitrary macro expansion. An unsupported path expression or a missing environment value in a resolved include is an extraction error, including with skip_unparsable = true. A plain scan_crate without a resolved build context still sees only the source it can follow without running a build script.
The cfg probe and actual wrapper build share their dependency output directory, so a generated API that depends on its OUT_DIR is scanned at the path the build uses. The files actually read by extraction enter the wrapper's artifact identity and generated module inputs. Changed generated contents invalidate the wrapper cache even when the build script's input lies outside the crate; previously loaded wrappers keep their own generation. Both @rust_crate and write_bindings_to_file use this resolved path.
One file, two modules
#[path = "shared.rs"] pub mod a; and the same for b compile one file as two distinct modules, and both are reported — under their own module paths, and under their own symbols (rustcall_a__shared_0fn / rustcall_b__shared_0fn), because the module path is part of every symbol (#300). The generated Julia module mirrors that: bindings.a.shared_fn() and bindings.b.shared_fn().
#[pymethods] is matched crate-wide
An inherent impl C is legal in any module that has C in scope, and in a multi-file crate the #[pyclass] and its #[pymethods] blocks routinely live in different files. Classes and blocks are therefore collected across the whole crate and married at the end: a block is attached to the class in its own module, or — failing that — to the one class of that name anywhere in the crate. Two things settle it exactly when several classes share a name: an explicit qualifier (impl a::C, resolved relative to the block's own module and then from the crate root) and the import that brought the name into scope (use crate::a::C;, including as aliases). Only when nothing disambiguates is the block dropped rather than attached to a guess.
An item marked both ways belongs to #[julia]
Since #279 #[julia] is additive, so an item may carry #[julia] and #[pyfunction] and get a Julia wrapper and a Python one. When both are present, #[julia] owns the C entry point: it already exports rustcall_<name>, so the PyO3 scan skips the item rather than describing a second wrapper under the same symbol.
The link plan
Before a wrapper crate can be built, one question has to be answered: will the resulting cdylib link, and will it load? That depends on whether pyo3 ends up in the build's dependency graph and with which features — which is Cargo's job, not RustCall's.
A build is named the way Cargo names one: a feature list and whether default features are on.
plan = RustCall.pyo3_link_plan("path/to/crate") # default features
plan = RustCall.pyo3_link_plan(crate; features = ["python"],
default_features = false) # a specific build
plan = RustCall.pyo3_link_plan(crate; release = false) # the debug profile
plan.mode # :python_free | :link_libpython | :unlinkable
plan.feature_flags # the Cargo flags that select this build
plan.crate_features # the crate's features, as Cargo resolved them
plan.pyo3_features # pyo3's resolved features (empty when absent)
plan.dependency_default_features # what its [dependencies] entry must say
plan.cfg_text # the configuration the crate is scanned under
plan.rpath # the interpreter's library directory
plan.interpreter # the interpreter PYO3_PYTHON is pinned to
plan.interpreter_config # what it reports about itself (version, ABI, library)
plan.resolved # whether Cargo answered
plan.reason # why this mode was chosen| mode | when | what the wrapper build does |
|---|---|---|
:python_free | pyo3 is not in this build's resolved graph | nothing links libpython |
:link_libpython | pyo3 is resolved | the cdylib hard-links libpython; the interpreter's library directory is added as -L and as an rpath, or the build refuses |
:unlinkable | pyo3's resolved features include extension-module | nothing usable can be built: refuse, with a message saying how to pick a different feature set |
What a :link_libpython build needs from the machine
A :link_libpython wrapper is only as portable as the Python it links. The build needs a library directory that holds something linkable: libpython3.x.so on Linux, libpython3.x.dylib or — for a framework Python — the Python3.framework bundle on macOS (the directory is then the framework prefix, PYTHONFRAMEWORKPREFIX), and the import library python3xy.lib on Windows; RustCall adds that directory as -L and, on Unix, as an rpath. On Windows the runtime python3xy.dll is a separate concern: it lives beside the interpreter, not in the import-library directory, and the generated module preloads it before the wrapper (see "Which Python" below). Where the directory comes from is decided by python_link_source(), in the order the "Which Python" section below spells out: the RUSTCALL_PYTHON_LIBDIR override, then pyo3's own configuration when it names one (PYO3_CROSS_LIB_DIR, the lib_dir of a PYO3_CONFIG_FILE — pyo3 then links without discovering an interpreter, and RustCall consults only the interpreter PYO3_PYTHON explicitly pins, if any, for the Windows runtime DLL), then the interpreter PYO3_PYTHON pins, then a loaded CondaPkg environment, and only then the python3 on PATH.
The two ways this goes wrong look different. With no interpreter and no configured directory the plan itself refuses, naming what it looked for. With an interpreter whose development package is missing, the directory it reports exists and is accepted — only isdir is checked — so the refusal comes later, from the linker: the wrapper build fails with the toolchain's own "library not found for -lpython3.x" (or the equivalent unresolved-symbol error). Either way the fix is the same: install python3-dev / python3-devel, or point PYO3_PYTHON (or RUSTCALL_PYTHON_LIBDIR) at a Python that ships the library.
The same requirement shapes RustCall's own test suite. The testsets that build and load a :link_libpython wrapper — in test/test_pyo3_wrapper.jl and the PyO3 cross-module case in test/test_module_symbols.jl — use one shared prerequisite helper. It checks the resolved plan and then checks for a linkable library in the selected directory (libpython3.x.so, libpython3.x.dylib or Python3.framework, or python3xy.lib). It logs an informative skipping message only when that prerequisite is absent. Once the directory is linkable, wrapper generation, Cargo, compiler, loading, and calls are hard failures; a wrapper regression cannot become a skip. The Ubuntu CI jobs have a linkable Python and run these testsets in full. test/test_pyo3_link_plan.jl and test/test_manifest.jl only compute the plan and always run, as do the scan-level assertions and every :python_free case (test/fixtures/sample_crate_pyo3_optional, sample_crate_pyo3, and examples/SampleCratePyO3.jl), which need no Python.
RustCall.pyo3_dependency_toml(plan, name, path) renders the [dependencies.<name>] entry the wrapper crate must write. That entry — not a build flag — is where a target crate's default features are switched off: cargo build --no-default-features applies to the package being built, so from the wrapper it disables the wrapper's defaults and leaves the target crate's (and therefore pyo3) enabled.
Cargo resolves the features, RustCall does not
Feature activation is transitive (api = ["python"], python = ["dep:pyo3"]), target-dependent ([target.'cfg(windows)'.dependencies]) and renameable (python = { package = "pyo3" }), and a #[cfg] predicate has Boolean structure (all, any, not). Re-implementing any of that in Julia gets it wrong in a new way for every crate shape, so the plan asks Cargo:
cargo tree -e features,normal -p <target>runs in a generated wrapper-shaped edition-2021 root and gives the resolved feature set of the target package and pyo3 — transitive closure, target tables and renames already applied. Requested features belong to the target dependency, not the wrapper itself. The target workspace's lockfile and root overrides are carried into this project. Both the root and edge filter matter: a resolver-1 target can unify pyo3's normal and build-dependency features when built on its own, although the wrapper's resolver keeps them separate. Build-sideextension-modulemust not make that wrapper unlinkable; unrelated workspace members must not activate features in its graph either.cargo rustc -- --print cfggives the configuration that build compiles under, whichscan_reporthands to the extractor so the crate is scanned in strict mode.#[cfg]and#[cfg_attr]on functions, structs, impls, methods and fields are then evaluated by the extractor's own evaluator, and the manifest contains exactly the items that build has.
Choosing a feature set
The plan answers for the build you name; it does not go hunting for a better one. RustCall.pyo3_feature_candidates(crate) says which features to consider, again from Cargo — one resolution per feature:
RustCall.pyo3_feature_candidates(crate)
# [(feature = "python", activates_pyo3 = true, extension_module = false),
# (feature = "extension", activates_pyo3 = true, extension_module = true)]That matters for a crate like this one:
[features]
default = ["extension"]
python = ["dep:pyo3"]
extension = ["python", "pyo3/extension-module"]Its default build is :unlinkable (extension pulls in extension-module), and so is --all-features. Turning defaults off gives :python_free — but that build compiles none of the crate's #[cfg(feature = "python")] API, so there is nothing to wrap. The build that works is neither of the obvious ones:
plan = RustCall.pyo3_link_plan(crate; features = ["python"], default_features = false)
plan.mode # :link_libpython
RustCall.scan_report(crate; features = ["python"], default_features = false)Enumerating "none / default / all" would never find it, which is why the feature set is the caller's to state and the candidates are there to inform the choice.
Without Cargo
When Cargo is unavailable or the crate does not resolve, the plan falls back to a deliberately conservative read of Cargo.toml that performs no feature resolution: any pyo3 declaration listing extension-module is :unlinkable, any other pyo3 declaration is :link_libpython, and only a crate with no pyo3 declaration at all is :python_free. plan.resolved is false and the reason says so. Renamed dependencies and [target.…] tables are still found — that is a manifest lookup, not resolution.
Why :link_libpython exists
Turning off extension-module is not enough to get a Python-free build. Verified in the #275 MWE on macOS: any build whose graph contains pyo3 links libpython — otool -L shows @rpath/Python3.framework/Versions/3.9/Python3 — and the cdylib then fails to dlopen unless the loader can find it. The only genuinely Python-free build is one in which pyo3 is not resolved at all — confirmed on Linux too: with the feature off, ldd on the wrapper .so shows only libc and libgcc.
Why :unlinkable refuses outright
extension-module tells pyo3 to leave libpython's symbols unresolved, for the Python interpreter to supply when it imports the module. A wrapper cdylib is never loaded that way, and the failure looks different on each platform — neither of them recoverable:
- macOS: the wrapper does not even link. pyo3 emits
-undefined dynamic_lookupthroughcargo:rustc-cdylib-link-argfrom its own build script, and that does not reach a dependent crate (which is why maturin sets the flag itself). Forcing the link produces a library that failsdlopenunderRTLD_NOWandRTLD_LAZY, because the missing symbols include data symbols (_PyBaseObject_Type,PyExc_*) that bind eagerly. - Linux: the wrapper links — ELF tolerates undefined symbols in a shared object — but
dlopenfails under both flags withundefined symbol: _Py_Dealloc.
So the plan refuses before the build rather than producing an artifact that cannot be loaded.
Windows is not Unix here
Two platform differences that the plan and the link flags both encode:
extension-moduleis a Unix-only blocker. A DLL must resolve every import at link time, so pyo3 links the interpreter's import library on Windows whether or not the feature is on, and the wrapper loads like any other:link_libpythonbuild.RustCall.extension_module_is_linkable()is the predicate.- Windows has no rpath.
pyo3_link_rustflagsemits only-L native=<dir>there, and the wrapper importspython3xy.dllby name — a file that lives beside the interpreter, not in thelibsdirectory it linked against, and that need not be on the Julia process'sPATH(a virtual environment or a CondaPYO3_PYTHON). So the plan records the DLL the interpreter itself is running (plan.runtime_libraries), and the generated module opens it, by full path, before the wrapper: the Windows loader satisfies an import by name from a module the process has already loaded. When no interpreter is consulted (PYO3_CONFIG_FILE,PYO3_CROSS_LIB_DIR) nothing is recorded and the DLL directory has to be onPATH. On Unix an rpath is recorded in the library itself and nothing else is needed.
The wrapper build applies these options from a generated build.rs (cargo:rustc-link-search, cargo:rustc-link-arg) rather than through RUSTFLAGS, so your own RUSTFLAGS, CARGO_ENCODED_RUSTFLAGS and [build] rustflags are left exactly as they are.
On macOS a framework build of Python is linked as @rpath/Python3.framework/Versions/3.x/Python3, so RustCall.python_library_dir() returns the directory containing the .framework rather than LIBDIR, which sits one level inside it.
Which Python
A :link_libpython wrapper involves two Pythons that must be the same one: the library directory the linker searches (plan.rpath) and the interpreter pyo3's build script configures itself for (PYO3_PYTHON, plan.interpreter). RustCall.python_link_source() decides them together, in this order:
RUSTCALL_PYTHON_LIBDIR, when you set it, is the directory whatever else says;- pyo3's own configuration, when it names one — a cross-compilation
PYO3_CROSS_LIB_DIR, or thelib_dirof aPYO3_CONFIG_FILE— is the directory, and no interpreter is consulted (pyo3 consults none either); PYO3_PYTHON, when you set it, is the interpreter — a virtual environment or a Conda interpreter is never replaced by the firstpython3onPATH— and the directory is what that interpreter itself reports;RUSTCALL_PYTHON_LIBDIRalone leaves the interpreter to thepython3onPATH;- a loaded CondaPkg (PythonCall) names both from its environment;
- otherwise the
python3/pythononPATHand the directory it reports.
The wrapper crate — and the cfg probe that decides what it can call — is written under RustCall's cache (RustCall.crate_target_directory(crate, :pyo3_wrapper), never the target crate's own target/, #486), seeded with the crate's Cargo.lock and root [patch] / [replace] tables, and built by a Cargo that runs in the crate's directory and names the wrapper with --manifest-path. So the crate's .cargo/config.toml, its pins and its overrides apply to the wrapper exactly as they apply to the crate itself — Cargo gives none of the three to a dependency of a root elsewhere — and a crate in a read-only tree can be wrapped. The pyo3_host = true build writes under crate_target_directory(crate, :pyo3_host) for the same reason; the integration guide's table lists every flavour.
The interpreter — its path and what it reports about itself (implementation, version, ABI tag, the library it links; plan.interpreter_config) — is part of the wrapper's artifact identity, so switching interpreters, or upgrading one in place behind the same path, rebuilds the wrapper rather than reusing one configured for the other; so are pyo3's other build inputs — every PYO3_* variable, and the contents of PYO3_CONFIG_FILE. The cfg probe the scan runs under follows the build profile (release = false probes the debug configuration, where debug_assertions is set), and it probes the crate as the wrapper's dependency — a temporary crate of the wrapper's shape, with the requested features in its dependency entry — so the crate's own [profile.*], which Cargo ignores for a dependency, does not leak into the scan.
Making pyo3 optional: the cfg_attr limitation
The :python_free mode is the clean path, but it is rarer than it looks. #[cfg_attr(feature = "python", ...)] works for the item attributes:
#[cfg_attr(feature = "python", pyfunction)]
pub fn add(a: i32, b: i32) -> i32 { a + b }The scan reads markers through cfg_attr (to any nesting depth), because the crate scan evaluates #[cfg] leniently — a feature predicate is deliberately left undecided — so a gated #[pyfunction] is found rather than silently skipped.
cfg_attr does not work for pyo3's inner attributes — new, staticmethod, classmethod, getter, setter, pyo3(get, set):
#[cfg_attr(feature = "python", pymethods)]
impl Point {
#[cfg_attr(feature = "python", new)] // error: cannot find attribute `new`
pub fn new(x: f64) -> Self { … }
}The outer macro runs before cfg_attr expands, so rustc reports cannot find attribute 'new' in this scope (and, for a static method, static method needs #[staticmethod] attribute). Real crates therefore make pyo3 mandatory, or duplicate items under #[cfg] — which makes :link_libpython the common case. Do not document cfg_attr as the way to make a crate's pyo3 dependency optional.
The consequence for Phase 2 is concrete: a crate whose pyo3 dependency is optional can expose free functions behind a feature and be wrapped with no Python at all, but it cannot have a #[pyclass] with methods, because those inner attributes cannot be gated. So :python_free wrappers are free-function wrappers, and a class always arrives through a :link_libpython build.
Example
The crates below are RustCall's test fixtures under test/fixtures/; the runnable example package is examples/SampleCratePyO3.jl, described last.
test/fixtures/sample_crate_pyo3_only is a crate that carries only PyO3 attributes: a mandatory pyo3 dependency with default-features = false, features = ["macros"], wrappable and skipped functions, a private-helper default, a Python-owned extends class, and a plain #[pyclass] with #[new], #[staticmethod], #[getter], #[setter], a String method, a PyResult method and #[pyo3(get, set)] fields, and a #[pymodule]. Its link plan is :link_libpython. It is what test/test_manifest.jl, test/test_pyo3_link_plan.jl and test/test_pyo3_wrapper.jl use.
test/fixtures/sample_crate_pyo3_optional is the optional-pyo3 counterpart: pyo3 is an optional dependency and only the #[pyfunction] markers are behind a feature. With the feature off its plan is :python_free and the build exposes nothing to PyO3, so nothing is wrapped; with features = ["python"] the same crate is wrapped in full.
test/fixtures/sample_crate_pyo3_mixed carries #[julia] and PyO3 markers together, one item marked both ways, and a [lib] name that differs from its package name.
Note that a class needs one #[pymethods] block unless the crate enables pyo3's multiple-pymethods feature; the scan matches every block it finds, but the crate has to compile for a wrapper to be built against it.
examples/SampleCratePyO3.jl is the dual-binding example: a Julia package with the crate deps/sample_crate_pyo3 embedded in it, one crate that serves Julia through #[julia] and Python through PyO3's own attributes, with pyo3 behind an optional python feature. It is the shape the section below migrates to (the test suite keeps its own copy as test/fixtures/sample_crate_pyo3).
Migrating from #[julia_pyo3]
#[julia_pyo3] was deprecated in 0.2.0 (#275 Phase 3) and removed in 0.3.0 (#312); the migration table that stood here through v0.4.x is in the v0.4.2 documentation. In one line: write #[julia] next to PyO3's own attributes on the same definition — #[julia] is additive (#279) — and spell the Python half with PyO3's full attribute surface.