Skip to main content

nautilus_core/python/
mod.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
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
16#![allow(clippy::doc_markdown, reason = "Python docstrings")]
17
18//! Python bindings and interoperability built using [`PyO3`](https://pyo3.rs).
19
20#![allow(
21    deprecated,
22    reason = "pyo3-stub-gen currently relies on PyO3 initialization helpers marked as deprecated"
23)]
24//!
25//! This sub-module groups together the Rust code that is *only* required when compiling the
26//! `python` feature flag. It provides thin adapters so that NautilusTrader functionality can be
27//! consumed from the `nautilus_trader` Python package without sacrificing type-safety or
28//! performance.
29
30pub mod casing;
31pub mod datetime;
32pub mod enums;
33pub mod params;
34pub mod parsing;
35pub mod serialization;
36/// String manipulation utilities for Python.
37pub mod string;
38pub mod uuid;
39pub mod version;
40
41use std::fmt::Display;
42
43use pyo3::{
44    Py,
45    conversion::IntoPyObjectExt,
46    exceptions::{
47        PyException, PyKeyError, PyNotImplementedError, PyRuntimeError, PyTypeError, PyValueError,
48    },
49    prelude::*,
50    types::PyString,
51    wrap_pyfunction,
52};
53use pyo3_stub_gen::derive::gen_stub_pyfunction;
54
55use crate::{
56    UUID4,
57    consts::{NAUTILUS_USER_AGENT, NAUTILUS_VERSION},
58    datetime::{
59        MILLISECONDS_IN_SECOND, NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND,
60        NANOSECONDS_IN_SECOND,
61    },
62};
63
64/// Safely clones a Python object by acquiring the GIL and properly managing reference counts.
65///
66/// This function exists to break reference cycles between Rust and Python that can occur
67/// when using `Arc<Py<PyAny>>` in callback-holding structs. The original design wrapped
68/// Python callbacks in `Arc` for thread-safe sharing, but this created circular references:
69///
70/// 1. Rust `Arc` holds Python objects → increases Python reference count.
71/// 2. Python objects might reference Rust objects → creates cycles.
72/// 3. Neither side can be garbage collected → memory leak.
73///
74/// By using plain `Py<PyAny>` with GIL-based cloning instead of `Arc<Py<PyAny>>`, we:
75/// - Avoid circular references between Rust and Python memory management.
76/// - Ensure proper Python reference counting under the GIL.
77/// - Allow both Rust and Python garbage collectors to work correctly.
78///
79/// # Safety
80///
81/// This function properly acquires the Python GIL before performing the clone operation,
82/// ensuring thread-safe access to the Python object and correct reference counting.
83#[must_use]
84pub fn clone_py_object(obj: &Py<PyAny>) -> Py<PyAny> {
85    Python::attach(|py| obj.clone_ref(py))
86}
87
88/// Calls a Python callback with a single argument, logging any errors.
89pub fn call_python(py: Python, callback: &Py<PyAny>, py_obj: Py<PyAny>) {
90    if let Err(e) = callback.call1(py, (py_obj,)) {
91        log::error!("Error calling Python: {e}");
92    }
93}
94
95/// Extend `IntoPyObjectExt` helper trait to unwrap `Py<PyAny>` after conversion.
96pub trait IntoPyObjectNautilusExt<'py>: IntoPyObjectExt<'py> {
97    /// Convert `self` into a [`Py<PyAny>`] while *panicking* if the conversion fails.
98    ///
99    /// This is a convenience wrapper around [`IntoPyObjectExt::into_py_any`] that avoids the
100    /// cumbersome `Result` handling when we are certain that the conversion cannot fail (for
101    /// instance when we are converting primitives or other types that already implement the
102    /// necessary PyO3 traits).
103    #[inline]
104    fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny> {
105        self.into_py_any(py)
106            .expect("Failed to convert type to Py<PyAny>")
107    }
108}
109
110impl<'py, T> IntoPyObjectNautilusExt<'py> for T where T: IntoPyObjectExt<'py> {}
111
112/// Gets the type name for the given Python `obj`.
113///
114/// # Errors
115///
116/// Returns a error if accessing the type name fails.
117pub fn get_pytype_name<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyString>> {
118    obj.get_type().name()
119}
120
121/// Converts any type that implements `Display` to a Python `ValueError`.
122pub fn to_pyvalue_err(e: impl Display) -> PyErr {
123    PyValueError::new_err(e.to_string())
124}
125
126/// Converts any type that implements `Display` to a Python `TypeError`.
127pub fn to_pytype_err(e: impl Display) -> PyErr {
128    PyTypeError::new_err(e.to_string())
129}
130
131/// Converts any type that implements `Display` to a Python `RuntimeError`.
132pub fn to_pyruntime_err(e: impl Display) -> PyErr {
133    PyRuntimeError::new_err(e.to_string())
134}
135
136/// Converts any type that implements `Display` to a Python `KeyError`.
137pub fn to_pykey_err(e: impl Display) -> PyErr {
138    PyKeyError::new_err(e.to_string())
139}
140
141/// Converts any type that implements `Display` to a Python `Exception`.
142pub fn to_pyexception(e: impl Display) -> PyErr {
143    PyException::new_err(e.to_string())
144}
145
146/// Converts any type that implements `Display` to a Python `NotImplementedError`.
147pub fn to_pynotimplemented_err(e: impl Display) -> PyErr {
148    PyNotImplementedError::new_err(e.to_string())
149}
150
151/// Return a value indicating whether the `obj` is a `PyCapsule`.
152///
153/// Parameters
154/// ----------
155/// obj : Any
156///     The object to check.
157///
158/// Returns
159/// -------
160/// bool
161#[gen_stub_pyfunction(module = "nautilus_trader.core")]
162#[pyfunction(name = "is_pycapsule")]
163#[allow(
164    clippy::needless_pass_by_value,
165    reason = "Python FFI requires owned types"
166)]
167#[allow(unsafe_code)]
168fn py_is_pycapsule(obj: Py<PyAny>) -> bool {
169    // SAFETY: obj.as_ptr() returns a valid Python object pointer
170    unsafe {
171        // PyCapsule_CheckExact checks if the object is exactly a PyCapsule
172        pyo3::ffi::PyCapsule_CheckExact(obj.as_ptr()) != 0
173    }
174}
175
176/// Loaded as `nautilus_pyo3.core`.
177///
178/// # Errors
179///
180/// Returns a `PyErr` if registering any module components fails.
181#[pymodule]
182#[rustfmt::skip]
183pub fn core(_: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
184    m.add(stringify!(NAUTILUS_VERSION), NAUTILUS_VERSION)?;
185    m.add(stringify!(NAUTILUS_USER_AGENT), NAUTILUS_USER_AGENT)?;
186    m.add(stringify!(MILLISECONDS_IN_SECOND), MILLISECONDS_IN_SECOND)?;
187    m.add(stringify!(NANOSECONDS_IN_SECOND), NANOSECONDS_IN_SECOND)?;
188    m.add(stringify!(NANOSECONDS_IN_MILLISECOND), NANOSECONDS_IN_MILLISECOND)?;
189    m.add(stringify!(NANOSECONDS_IN_MICROSECOND), NANOSECONDS_IN_MICROSECOND)?;
190    m.add_class::<UUID4>()?;
191    m.add_function(wrap_pyfunction!(py_is_pycapsule, m)?)?;
192    m.add_function(wrap_pyfunction!(casing::py_convert_to_snake_case, m)?)?;
193    m.add_function(wrap_pyfunction!(string::py_mask_api_key, m)?)?;
194    m.add_function(wrap_pyfunction!(datetime::py_secs_to_nanos, m)?)?;
195    m.add_function(wrap_pyfunction!(datetime::py_secs_to_millis, m)?)?;
196    m.add_function(wrap_pyfunction!(datetime::py_millis_to_nanos, m)?)?;
197    m.add_function(wrap_pyfunction!(datetime::py_micros_to_nanos, m)?)?;
198    m.add_function(wrap_pyfunction!(datetime::py_nanos_to_secs, m)?)?;
199    m.add_function(wrap_pyfunction!(datetime::py_nanos_to_millis, m)?)?;
200    m.add_function(wrap_pyfunction!(datetime::py_nanos_to_micros, m)?)?;
201    m.add_function(wrap_pyfunction!(datetime::py_unix_nanos_to_iso8601, m)?)?;
202    m.add_function(wrap_pyfunction!(datetime::py_last_weekday_nanos, m)?)?;
203    m.add_function(wrap_pyfunction!(datetime::py_is_within_last_24_hours, m)?)?;
204    Ok(())
205}