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