Skip to main content

fidius_python/
interpreter.rs

1// Copyright 2026 Colliery, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Embedded interpreter lifecycle.
16//!
17//! Fidius-python links libpython through PyO3's `auto-initialize` feature.
18//! The interpreter is brought up lazily on first use and lives for the
19//! remainder of the host process — fidius does not currently support
20//! tearing it down or reinitialising it. This matches cloacina's pattern.
21//!
22//! All Python work is gated by PyO3's `Python::with_gil`, which is the
23//! correct concurrency primitive for embedded interpreters: there is no
24//! separate `Mutex<PyInterpreter>` to manage.
25
26use std::sync::Once;
27
28use tracing::trace;
29
30static INIT: Once = Once::new();
31
32/// Idempotent: ensure the embedded Python interpreter is initialised.
33///
34/// `auto-initialize` already brings it up on the first `Python::with_gil`
35/// call, so this function is mostly a documented entry point and a tracing
36/// hook for diagnosing "did Python actually start up" issues. Calling it
37/// repeatedly is cheap.
38pub fn ensure_initialized() {
39    INIT.call_once(|| {
40        trace!("initialising embedded Python interpreter");
41        // Touching `Python::with_gil` triggers PyO3's auto-initialize.
42        pyo3::Python::with_gil(|_py| {
43            trace!("embedded Python interpreter is ready");
44        });
45    });
46}