nautilus_core/python/
mod.rs

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