Skip to main content

pyo3/
marker.rs

1// TODO https://github.com/PyO3/pyo3/issues/5487
2#![allow(clippy::undocumented_unsafe_blocks)]
3
4//! Fundamental properties of objects tied to the Python interpreter.
5//!
6//! The Python interpreter is not thread-safe. To protect the Python interpreter in multithreaded
7//! scenarios there is a global lock, the *global interpreter lock* (hereafter referred to as *GIL*)
8//! that must be held to safely interact with Python objects. This is why in PyO3 when you acquire
9//! the GIL you get a [`Python`] marker token that carries the *lifetime* of holding the GIL and all
10//! borrowed references to Python objects carry this lifetime as well. This will statically ensure
11//! that you can never use Python objects after dropping the lock - if you mess this up it will be
12//! caught at compile time and your program will fail to compile.
13//!
14//! It also supports this pattern that many extension modules employ:
15//! - Drop the GIL, so that other Python threads can acquire it and make progress themselves
16//! - Do something independently of the Python interpreter, like IO, a long running calculation or
17//!   awaiting a future
18//! - Once that is done, reacquire the GIL
19//!
20//! That API is provided by [`Python::detach`] and enforced via the [`Ungil`] bound on the
21//! closure and the return type. This is done by relying on the [`Send`] auto trait. `Ungil` is
22//! defined as the following:
23//!
24//! ```rust,no_run
25//! # #![allow(dead_code)]
26//! pub unsafe trait Ungil {}
27//!
28//! unsafe impl<T: Send> Ungil for T {}
29//! ```
30//!
31//! We piggy-back off the `Send` auto trait because it is not possible to implement custom auto
32//! traits on stable Rust. This is the solution which enables it for as many types as possible while
33//! making the API usable.
34//!
35//! In practice this API works quite well, but it comes with some drawbacks:
36//!
37//! ## Drawbacks
38//!
39//! There is no reason to prevent `!Send` types like [`Rc`] from crossing the closure. After all,
40//! [`Python::detach`] just lets other Python threads run - it does not itself launch a new
41//! thread.
42//!
43//! ```rust, compile_fail
44//! # #[cfg(feature = "nightly")]
45//! # compile_error!("this actually works on nightly")
46//! use pyo3::prelude::*;
47//! use alloc::rc::Rc;
48//!
49//! fn main() {
50//!     Python::attach(|py| {
51//!         let rc = Rc::new(5);
52//!
53//!         py.detach(|| {
54//!             // This would actually be fine...
55//!             println!("{:?}", *rc);
56//!         });
57//!     });
58//! }
59//! ```
60//!
61//! Because we are using `Send` for something it's not quite meant for, other code that
62//! (correctly) upholds the invariants of [`Send`] can cause problems.
63//!
64//! [`SendWrapper`] is one of those. Per its documentation:
65//!
66//! > A wrapper which allows you to move around non-Send-types between threads, as long as you
67//! > access the contained value only from within the original thread and make sure that it is
68//! > dropped from within the original thread.
69//!
70//! This will "work" to smuggle Python references across the closure, because we're not actually
71//! doing anything with threads:
72//!
73//! ```rust, no_run
74//! use pyo3::prelude::*;
75//! use pyo3::types::PyString;
76//! use send_wrapper::SendWrapper;
77//!
78//! Python::attach(|py| {
79//!     let string = PyString::new(py, "foo");
80//!
81//!     let wrapped = SendWrapper::new(string);
82//!
83//!     py.detach(|| {
84//! # #[cfg(not(feature = "nightly"))]
85//! # {
86//!         // 💥 Unsound! 💥
87//!         let smuggled: &Bound<'_, PyString> = &*wrapped;
88//!         println!("{:?}", smuggled);
89//! # }
90//!     });
91//! });
92//! ```
93//!
94//! For now the answer to that is "don't do that".
95//!
96//! # A proper implementation using an auto trait
97//!
98//! However on nightly Rust and when PyO3's `nightly` feature is
99//! enabled, `Ungil` is defined as the following:
100//!
101//! ```rust,no_run
102//! # #[cfg(any())]
103//! # {
104//! #![feature(auto_traits, negative_impls)]
105//!
106//! pub unsafe auto trait Ungil {}
107//!
108//! // It is unimplemented for the `Python` struct and Python objects.
109//! impl !Ungil for Python<'_> {}
110//! impl !Ungil for ffi::PyObject {}
111//!
112//! // `Py` wraps it in  a safe api, so this is OK
113//! unsafe impl<T> Ungil for Py<T> {}
114//! # }
115//! ```
116//!
117//! With this feature enabled, the above two examples will start working and not working, respectively.
118//!
119//! [`SendWrapper`]: https://docs.rs/send_wrapper/latest/send_wrapper/struct.SendWrapper.html
120//! [`Rc`]: alloc::rc::Rc
121//! [`Py`]: Py
122use crate::conversion::IntoPyObject;
123use crate::err::{self, PyResult};
124use crate::internal::state::{AttachGuard, SuspendAttach};
125use crate::types::any::PyAnyMethods;
126use crate::types::{
127    PyAny, PyCode, PyCodeMethods, PyDict, PyEllipsis, PyModule, PyNone, PyNotImplemented, PyString,
128    PyType,
129};
130use crate::version::PythonVersionInfo;
131use crate::{ffi, Bound, Py, PyTypeInfo};
132use core::ffi::CStr;
133use core::marker::PhantomData;
134use std::sync::LazyLock;
135
136/// Types that are safe to access while the GIL is not held.
137///
138/// # Safety
139///
140/// The type must not carry borrowed Python references or, if it does, not allow access to them if
141/// the GIL is not held.
142///
143/// See the [module-level documentation](self) for more information.
144///
145/// # Examples
146///
147/// This tracking is currently imprecise as it relies on the [`Send`] auto trait on stable Rust.
148/// For example, an `Rc` smart pointer should be usable without the GIL, but we currently prevent that:
149///
150/// ```compile_fail
151/// # use pyo3::prelude::*;
152/// use alloc::rc::Rc;
153///
154/// Python::attach(|py| {
155///     let rc = Rc::new(42);
156///
157///     py.detach(|| {
158///         println!("{:?}", rc);
159///     });
160/// });
161/// ```
162///
163/// This also implies that the interplay between `attach` and `detach` is unsound, for example
164/// one can circumvent this protection using the [`send_wrapper`](https://docs.rs/send_wrapper/) crate:
165///
166/// ```no_run
167/// # use pyo3::prelude::*;
168/// # use pyo3::types::PyString;
169/// use send_wrapper::SendWrapper;
170///
171/// Python::attach(|py| {
172///     let string = PyString::new(py, "foo");
173///
174///     let wrapped = SendWrapper::new(string);
175///
176///     py.detach(|| {
177///         let sneaky: &Bound<'_, PyString> = &*wrapped;
178///
179///         println!("{:?}", sneaky);
180///     });
181/// });
182/// ```
183///
184/// Fixing this loophole on stable Rust has significant ergonomic issues, but it is fixed when using
185/// nightly Rust and the `nightly` feature, c.f. [#2141](https://github.com/PyO3/pyo3/issues/2141).
186#[cfg_attr(docsrs, doc(cfg(all())))] // Hide the cfg flag
187#[cfg(not(feature = "nightly"))]
188pub unsafe trait Ungil {}
189
190#[cfg_attr(docsrs, doc(cfg(all())))] // Hide the cfg flag
191#[cfg(not(feature = "nightly"))]
192unsafe impl<T: Send> Ungil for T {}
193
194#[cfg(feature = "nightly")]
195mod nightly {
196    macro_rules! define {
197        ($($tt:tt)*) => { $($tt)* }
198    }
199
200    define! {
201        /// Types that are safe to access while the GIL is not held.
202        ///
203        /// # Safety
204        ///
205        /// The type must not carry borrowed Python references or, if it does, not allow access to them if
206        /// the GIL is not held.
207        ///
208        /// See the [module-level documentation](self) for more information.
209        ///
210        /// # Examples
211        ///
212        /// Types which are `Ungil` cannot be used in contexts where the GIL was released, e.g.
213        ///
214        /// ```compile_fail
215        /// # use pyo3::prelude::*;
216        /// # use pyo3::types::PyString;
217        /// Python::attach(|py| {
218        ///     let string = PyString::new(py, "foo");
219        ///
220        ///     py.detach(|| {
221        ///         println!("{:?}", string);
222        ///     });
223        /// });
224        /// ```
225        ///
226        /// This applies to the [`Python`] token itself as well, e.g.
227        ///
228        /// ```compile_fail
229        /// # use pyo3::prelude::*;
230        /// Python::attach(|py| {
231        ///     py.detach(|| {
232        ///         drop(py);
233        ///     });
234        /// });
235        /// ```
236        ///
237        /// On nightly Rust, this is not based on the [`Send`] auto trait and hence we are able
238        /// to prevent incorrectly circumventing it using e.g. the [`send_wrapper`](https://docs.rs/send_wrapper/) crate:
239        ///
240        /// ```compile_fail
241        /// # use pyo3::prelude::*;
242        /// # use pyo3::types::PyString;
243        /// use send_wrapper::SendWrapper;
244        ///
245        /// Python::attach(|py| {
246        ///     let string = PyString::new(py, "foo");
247        ///
248        ///     let wrapped = SendWrapper::new(string);
249        ///
250        ///     py.detach(|| {
251        ///         let sneaky: &PyString = *wrapped;
252        ///
253        ///         println!("{:?}", sneaky);
254        ///     });
255        /// });
256        /// ```
257        ///
258        /// This also enables using non-[`Send`] types in `detach`,
259        /// at least if they are not also bound to the GIL:
260        ///
261        /// ```rust
262        /// # use pyo3::prelude::*;
263        /// use std::rc::Rc;
264        ///
265        /// Python::attach(|py| {
266        ///     let rc = Rc::new(42);
267        ///
268        ///     py.detach(|| {
269        ///         println!("{:?}", rc);
270        ///     });
271        /// });
272        /// ```
273        pub unsafe auto trait Ungil {}
274
275        impl !Ungil for crate::Python<'_> {}
276
277        // This means that PyString, PyList, etc all inherit !Ungil from  this.
278        impl !Ungil for crate::PyAny {}
279
280        impl<T> !Ungil for crate::PyRef<'_, T> {}
281        impl<T> !Ungil for crate::PyRefMut<'_, T> {}
282
283        // FFI pointees
284        impl !Ungil for crate::ffi::PyObject {}
285        impl !Ungil for crate::ffi::PyLongObject {}
286
287        impl !Ungil for crate::ffi::PyThreadState {}
288        impl !Ungil for crate::ffi::PyInterpreterState {}
289        #[cfg(not(any(PyPy, GraalPy)))]
290        impl !Ungil for crate::ffi::PyWeakReference {}
291        impl !Ungil for crate::ffi::PyFrameObject {}
292        impl !Ungil for crate::ffi::PyCodeObject {}
293        #[cfg(all(not(PyPy), not(Py_LIMITED_API)))]
294        impl !Ungil for crate::ffi::PyDictKeysObject {}
295        #[cfg(not(any(Py_LIMITED_API, Py_3_10)))]
296        impl !Ungil for crate::ffi::PyArena {}
297    }
298}
299
300#[cfg(feature = "nightly")]
301pub use nightly::Ungil;
302
303/// A marker token that represents holding the GIL.
304///
305/// It serves three main purposes:
306/// - It provides a global API for the Python interpreter, such as [`Python::eval`].
307/// - It can be passed to functions that require a proof of holding the GIL, such as
308///   [`Py::clone_ref`](crate::Py::clone_ref).
309/// - Its lifetime represents the scope of holding the GIL which can be used to create Rust
310///   references that are bound to it, such as [`Bound<'py, PyAny>`].
311///
312/// Note that there are some caveats to using it that you might need to be aware of. See the
313/// [Deadlocks](#deadlocks) and [Releasing and freeing memory](#releasing-and-freeing-memory)
314/// paragraphs for more information about that.
315///
316/// # Obtaining a Python token
317///
318/// The following are the recommended ways to obtain a [`Python<'py>`] token, in order of preference:
319/// - If you already have something with a lifetime bound to the GIL, such as [`Bound<'py, PyAny>`], you can
320///   use its `.py()` method to get a token.
321/// - In a function or method annotated with [`#[pyfunction]`](crate::pyfunction) or [`#[pymethods]`](crate::pymethods) you can declare it
322///   as a parameter, and PyO3 will pass in the token when Python code calls it.
323/// - When you need to acquire the GIL yourself, such as when calling Python code from Rust, you
324///   should call [`Python::attach`] to do that and pass your code as a closure to it.
325///
326/// The first two options are zero-cost; [`Python::attach`] requires runtime checking and may need to block
327/// to acquire the GIL.
328///
329/// # Deadlocks
330///
331/// Note that the GIL can be temporarily released by the Python interpreter during a function call
332/// (e.g. importing a module). In general, you don't need to worry about this because the GIL is
333/// reacquired before returning to the Rust code:
334///
335/// ```text
336/// `Python` exists   |=====================================|
337/// GIL actually held |==========|         |================|
338/// Rust code running |=======|                |==|  |======|
339/// ```
340///
341/// This behaviour can cause deadlocks when trying to lock a Rust mutex while holding the GIL:
342///
343///  * Thread 1 acquires the GIL
344///  * Thread 1 locks a mutex
345///  * Thread 1 makes a call into the Python interpreter which releases the GIL
346///  * Thread 2 acquires the GIL
347///  * Thread 2 tries to locks the mutex, blocks
348///  * Thread 1's Python interpreter call blocks trying to reacquire the GIL held by thread 2
349///
350/// To avoid deadlocking, you should release the GIL before trying to lock a mutex or `await`ing in
351/// asynchronous code, e.g. with [`Python::detach`].
352///
353/// # Releasing and freeing memory
354///
355/// The [`Python<'py>`] type can be used to create references to variables owned by the Python
356/// interpreter, using functions such as [`Python::eval`] and [`PyModule::import`].
357#[derive(Copy, Clone)]
358pub struct Python<'py>(PhantomData<&'py AttachGuard>, PhantomData<NotSend>);
359
360/// A marker type that makes the type !Send.
361/// Workaround for lack of !Send on stable (<https://github.com/rust-lang/rust/issues/68318>).
362struct NotSend(PhantomData<*mut Python<'static>>);
363
364impl Python<'_> {
365    /// Acquires the global interpreter lock, allowing access to the Python interpreter. The
366    /// provided closure `F` will be executed with the acquired `Python` marker token.
367    ///
368    /// If implementing [`#[pymethods]`](crate::pymethods) or [`#[pyfunction]`](crate::pyfunction),
369    /// declare `py: Python` as an argument. PyO3 will pass in the token to grant access to the GIL
370    /// context in which the function is running, avoiding the need to call `attach`.
371    ///
372    /// If the [`auto-initialize`] feature is enabled and the Python runtime is not already
373    /// initialized, this function will initialize it. See
374    #[cfg_attr(
375        not(any(PyPy, GraalPy)),
376        doc = "[`Python::initialize`](crate::marker::Python::initialize)"
377    )]
378    #[cfg_attr(PyPy, doc = "`Python::initialize")]
379    /// for details.
380    ///
381    /// If the current thread does not yet have a Python "thread state" associated with it,
382    /// a new one will be automatically created before `F` is executed and destroyed after `F`
383    /// completes.
384    ///
385    /// # Panics
386    ///
387    /// - If the [`auto-initialize`] feature is not enabled and the Python interpreter is not
388    ///   initialized.
389    /// - If the Python interpreter is in the process of [shutting down].
390    /// - If the current thread is currently in the middle of a GC traversal (i.e. called from
391    ///   within a `__traverse__` method).
392    ///
393    /// To avoid possible initialization or panics if calling in a context where the Python
394    /// interpreter might be unavailable, consider using [`Python::try_attach`].
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// use pyo3::prelude::*;
400    ///
401    /// # fn main() -> PyResult<()> {
402    /// Python::attach(|py| -> PyResult<()> {
403    ///     let x: i32 = py.eval(c"5", None, None)?.extract()?;
404    ///     assert_eq!(x, 5);
405    ///     Ok(())
406    /// })
407    /// # }
408    /// ```
409    ///
410    /// [`auto-initialize`]: https://pyo3.rs/main/features.html#auto-initialize
411    /// [shutting down]: https://docs.python.org/3/glossary.html#term-interpreter-shutdown
412    #[inline]
413    #[track_caller]
414    pub fn attach<F, R>(f: F) -> R
415    where
416        F: for<'py> FnOnce(Python<'py>) -> R,
417    {
418        let guard = AttachGuard::attach();
419        f(guard.python())
420    }
421
422    /// Variant of [`Python::attach`] which will return without attaching to the Python
423    /// interpreter if the interpreter is in a state where it cannot be attached to:
424    ///
425    /// - If the Python interpreter is not initialized.
426    /// - If the Python interpreter is in the process of [shutting down].
427    /// - If the current thread is currently in the middle of a GC traversal (i.e. called from
428    ///   within a `__traverse__` method).
429    ///
430    /// Unlike `Python::attach`, this function will not initialize the Python interpreter,
431    /// even if the [`auto-initialize`] feature is enabled.
432    ///
433    /// Note that due to the nature of the underlying Python APIs used to implement this,
434    /// the behavior is currently provided on a best-effort basis; it is expected that a
435    /// future CPython version will introduce APIs which guarantee this behaviour. This
436    /// function is still recommended for use in the meanwhile as it provides the best
437    /// possible behaviour and should transparently change to an optimal implementation
438    /// once such APIs are available.
439    ///
440    /// [`auto-initialize`]: https://pyo3.rs/main/features.html#auto-initialize
441    /// [shutting down]: https://docs.python.org/3/glossary.html#term-interpreter-shutdown
442    #[inline]
443    #[track_caller]
444    pub fn try_attach<F, R>(f: F) -> Option<R>
445    where
446        F: for<'py> FnOnce(Python<'py>) -> R,
447    {
448        let guard = AttachGuard::try_attach().ok()?;
449        Some(f(guard.python()))
450    }
451
452    /// Prepares the use of Python.
453    ///
454    /// If the Python interpreter is not already initialized, this function will initialize it with
455    /// signal handling disabled (Python will not raise the `KeyboardInterrupt` exception). Python
456    /// signal handling depends on the notion of a 'main thread', which must be the thread that
457    /// initializes the Python interpreter.
458    ///
459    /// If the Python interpreter is already initialized, this function has no effect.
460    ///
461    /// This function is unavailable under PyPy because PyPy cannot be embedded in Rust (or any other
462    /// software). Support for this is tracked on the
463    /// [PyPy issue tracker](https://github.com/pypy/pypy/issues/3836).
464    ///
465    /// # Examples
466    /// ```rust
467    /// use pyo3::prelude::*;
468    ///
469    /// # fn main() -> PyResult<()> {
470    /// Python::initialize();
471    /// Python::attach(|py| py.run(c"print('Hello World')", None, None))
472    /// # }
473    /// ```
474    #[cfg(not(any(PyPy, GraalPy)))]
475    pub fn initialize() {
476        crate::interpreter_lifecycle::initialize();
477    }
478
479    /// Like [`Python::attach`] except Python interpreter state checking is skipped.
480    ///
481    /// Normally when attaching to the Python interpreter, PyO3 checks that it is in
482    /// an appropriate state (e.g. it is fully initialized). This function skips
483    /// those checks.
484    ///
485    /// # Safety
486    ///
487    /// If [`Python::attach`] would succeed, it is safe to call this function.
488    #[inline]
489    #[track_caller]
490    pub unsafe fn attach_unchecked<F, R>(f: F) -> R
491    where
492        F: for<'py> FnOnce(Python<'py>) -> R,
493    {
494        let guard = unsafe { AttachGuard::attach_unchecked() };
495
496        f(guard.python())
497    }
498}
499
500impl<'py> Python<'py> {
501    /// Temporarily releases the GIL, thus allowing other Python threads to run. The GIL will be
502    /// reacquired when `F`'s scope ends.
503    ///
504    /// If you don't need to touch the Python
505    /// interpreter for some time and have other Python threads around, this will let you run
506    /// Rust-only code while letting those other Python threads make progress.
507    ///
508    /// Only types that implement [`Ungil`] can cross the closure. See the
509    /// [module level documentation](self) for more information.
510    ///
511    /// If you need to pass Python objects into the closure you can use [`Py`]`<T>`to create a
512    /// reference independent of the GIL lifetime. However, you cannot do much with those without a
513    /// [`Python`] token, for which you'd need to reacquire the GIL.
514    ///
515    /// # Example: Releasing the GIL while running a computation in Rust-only code
516    ///
517    /// ```
518    /// use pyo3::prelude::*;
519    ///
520    /// #[pyfunction]
521    /// fn sum_numbers(py: Python<'_>, numbers: Vec<u32>) -> PyResult<u32> {
522    ///     // We release the GIL here so any other Python threads get a chance to run.
523    ///     py.detach(move || {
524    ///         // An example of an "expensive" Rust calculation
525    ///         let sum = numbers.iter().sum();
526    ///
527    ///         Ok(sum)
528    ///     })
529    /// }
530    /// #
531    /// # fn main() -> PyResult<()> {
532    /// #     Python::attach(|py| -> PyResult<()> {
533    /// #         let fun = pyo3::wrap_pyfunction!(sum_numbers, py)?;
534    /// #         let res = fun.call1((vec![1_u32, 2, 3],))?;
535    /// #         assert_eq!(res.extract::<u32>()?, 6_u32);
536    /// #         Ok(())
537    /// #     })
538    /// # }
539    /// ```
540    ///
541    /// Please see the [Parallelism] chapter of the guide for a thorough discussion of using
542    /// [`Python::detach`] in this manner.
543    ///
544    /// # Example: Passing borrowed Python references into the closure is not allowed
545    ///
546    /// ```compile_fail
547    /// use pyo3::prelude::*;
548    /// use pyo3::types::PyString;
549    ///
550    /// fn parallel_print(py: Python<'_>) {
551    ///     let s = PyString::new(py, "This object cannot be accessed without holding the GIL >_<");
552    ///     py.detach(move || {
553    ///         println!("{:?}", s); // This causes a compile error.
554    ///     });
555    /// }
556    /// ```
557    ///
558    /// [`Py`]: crate::Py
559    /// [`PyString`]: crate::types::PyString
560    /// [auto-traits]: https://doc.rust-lang.org/nightly/unstable-book/language-features/auto-traits.html
561    /// [Parallelism]: https://pyo3.rs/main/parallelism.html
562    pub fn detach<T, F>(self, f: F) -> T
563    where
564        F: Ungil + FnOnce() -> T,
565        T: Ungil,
566    {
567        // Use a guard pattern to handle reacquiring the GIL,
568        // so that the GIL will be reacquired even if `f` panics.
569        // The `Send` bound on the closure prevents the user from
570        // transferring the `Python` token into the closure.
571        let _guard = unsafe { SuspendAttach::new() };
572        f()
573    }
574
575    /// Evaluates a Python expression in the given context and returns the result.
576    ///
577    /// If `globals` is `None`, it defaults to Python module `__main__`.
578    /// If `locals` is `None`, it defaults to the value of `globals`.
579    ///
580    /// If `globals` doesn't contain `__builtins__`, default `__builtins__`
581    /// will be added automatically.
582    ///
583    /// # Examples
584    ///
585    /// ```
586    /// # use pyo3::prelude::*;
587    /// # Python::attach(|py| {
588    /// let result = py.eval(c"[i * 10 for i in range(5)]", None, None).unwrap();
589    /// let res: Vec<i64> = result.extract().unwrap();
590    /// assert_eq!(res, vec![0, 10, 20, 30, 40])
591    /// # });
592    /// ```
593    pub fn eval(
594        self,
595        code: &CStr,
596        globals: Option<&Bound<'py, PyDict>>,
597        locals: Option<&Bound<'py, PyDict>>,
598    ) -> PyResult<Bound<'py, PyAny>> {
599        let code = PyCode::compile(self, code, c"<string>", crate::types::PyCodeInput::Eval)?;
600        code.run(globals, locals)
601    }
602
603    /// Executes one or more Python statements in the given context.
604    ///
605    /// If `globals` is `None`, it defaults to Python module `__main__`.
606    /// If `locals` is `None`, it defaults to the value of `globals`.
607    ///
608    /// If `globals` doesn't contain `__builtins__`, default `__builtins__`
609    /// will be added automatically.
610    ///
611    /// # Examples
612    /// ```
613    /// use pyo3::{
614    ///     prelude::*,
615    ///     types::{PyBytes, PyDict},
616    /// };
617    /// Python::attach(|py| {
618    ///     let locals = PyDict::new(py);
619    ///     py.run(cr#"
620    /// import base64
621    /// s = 'Hello Rust!'
622    /// ret = base64.b64encode(s.encode('utf-8'))
623    /// "#,
624    ///         None,
625    ///         Some(&locals),
626    ///     )
627    ///     .unwrap();
628    ///     let ret = locals.get_item("ret").unwrap().unwrap();
629    ///     let b64 = ret.cast::<PyBytes>().unwrap();
630    ///     assert_eq!(b64.as_bytes(), b"SGVsbG8gUnVzdCE=");
631    /// });
632    /// ```
633    ///
634    /// You can use [`py_run!`](macro.py_run.html) for a handy alternative of `run`
635    /// if you don't need `globals` and unwrapping is OK.
636    pub fn run(
637        self,
638        code: &CStr,
639        globals: Option<&Bound<'py, PyDict>>,
640        locals: Option<&Bound<'py, PyDict>>,
641    ) -> PyResult<()> {
642        let code = PyCode::compile(self, code, c"<string>", crate::types::PyCodeInput::File)?;
643        code.run(globals, locals).map(|obj| {
644            debug_assert!(obj.is_none());
645        })
646    }
647
648    /// Gets the Python type object for type `T`.
649    #[inline]
650    pub fn get_type<T>(self) -> Bound<'py, PyType>
651    where
652        T: PyTypeInfo,
653    {
654        T::type_object(self)
655    }
656
657    /// Imports the Python module with the specified name.
658    pub fn import<N>(self, name: N) -> PyResult<Bound<'py, PyModule>>
659    where
660        N: IntoPyObject<'py, Target = PyString>,
661    {
662        PyModule::import(self, name)
663    }
664
665    /// Gets the Python builtin value `None`.
666    #[allow(non_snake_case)] // the Python keyword starts with uppercase
667    #[inline]
668    pub fn None(self) -> Py<PyAny> {
669        PyNone::get(self).to_owned().into_any().unbind()
670    }
671
672    /// Gets the Python builtin value `Ellipsis`, or `...`.
673    #[allow(non_snake_case)] // the Python keyword starts with uppercase
674    #[inline]
675    pub fn Ellipsis(self) -> Py<PyAny> {
676        PyEllipsis::get(self).to_owned().into_any().unbind()
677    }
678
679    /// Gets the Python builtin value `NotImplemented`.
680    #[allow(non_snake_case)] // the Python keyword starts with uppercase
681    #[inline]
682    pub fn NotImplemented(self) -> Py<PyAny> {
683        PyNotImplemented::get(self).to_owned().into_any().unbind()
684    }
685
686    /// Deprecated version of [Python::version_str].
687    #[deprecated(since = "0.29.0", note = "use Python::version_str instead")]
688    pub fn version(self) -> &'static str {
689        Python::version_str()
690    }
691
692    /// Gets the running Python interpreter version as a string.
693    ///
694    /// # Examples
695    /// ```rust
696    /// # use pyo3::Python;
697    /// assert!(Python::version_str().starts_with("3."));
698    /// ```
699    pub fn version_str() -> &'static str {
700        static VERSION: LazyLock<&'static str> = LazyLock::new(|| unsafe {
701            CStr::from_ptr(ffi::Py_GetVersion())
702                .to_str()
703                .expect("Python version string not UTF-8")
704        });
705
706        &VERSION
707    }
708
709    /// Gets the running Python interpreter version as a struct similar to
710    /// `sys.version_info`.
711    ///
712    /// # Examples
713    /// ```rust
714    /// # use pyo3::Python;
715    /// Python::attach(|py| {
716    ///     // PyO3 supports Python 3.9 and up.
717    ///     assert!(py.version_info() >= (3, 9));
718    ///     assert!(py.version_info() >= (3, 9, 0));
719    /// });
720    /// ```
721    pub fn version_info(self) -> PythonVersionInfo {
722        let version_str = Python::version_str();
723
724        // Portion of the version string returned by Py_GetVersion up to the first space is the
725        // version number.
726        let version_number_str = version_str.split(' ').next().unwrap_or(version_str);
727
728        PythonVersionInfo::from_str(version_number_str).unwrap()
729    }
730
731    /// Lets the Python interpreter check and handle any pending signals. This will invoke the
732    /// corresponding signal handlers registered in Python (if any).
733    ///
734    /// Returns `Err(`[`PyErr`](crate::PyErr)`)` if any signal handler raises an exception.
735    ///
736    /// These signals include `SIGINT` (normally raised by CTRL + C), which by default raises
737    /// `KeyboardInterrupt`. For this reason it is good practice to call this function regularly
738    /// as part of long-running Rust functions so that users can cancel it.
739    ///
740    /// # Example
741    ///
742    /// ```rust,no_run
743    /// # #![allow(dead_code)] // this example is quite impractical to test
744    /// use pyo3::prelude::*;
745    ///
746    /// # fn main() {
747    /// #[pyfunction]
748    /// fn loop_forever(py: Python<'_>) -> PyResult<()> {
749    ///     loop {
750    ///         // As this loop is infinite it should check for signals every once in a while.
751    ///         // Using `?` causes any `PyErr` (potentially containing `KeyboardInterrupt`)
752    ///         // to break out of the loop.
753    ///         py.check_signals()?;
754    ///
755    ///         // do work here
756    ///         # break Ok(()) // don't actually loop forever
757    ///     }
758    /// }
759    /// # }
760    /// ```
761    ///
762    /// # Note
763    ///
764    /// This function calls [`PyErr_CheckSignals()`][1] which in turn may call signal handlers.
765    /// As Python's [`signal`][2] API allows users to define custom signal handlers, calling this
766    /// function allows arbitrary Python code inside signal handlers to run.
767    ///
768    /// If the function is called from a non-main thread, or under a non-main Python interpreter,
769    /// it does nothing yet still returns `Ok(())`.
770    ///
771    /// [1]: https://docs.python.org/3/c-api/exceptions.html?highlight=pyerr_checksignals#c.PyErr_CheckSignals
772    /// [2]: https://docs.python.org/3/library/signal.html
773    pub fn check_signals(self) -> PyResult<()> {
774        err::error_on_minusone(self, unsafe { ffi::PyErr_CheckSignals() })
775    }
776}
777
778impl<'unbound> Python<'unbound> {
779    /// Unsafely creates a Python token with an unbounded lifetime.
780    ///
781    /// Many of PyO3 APIs use [`Python<'_>`] as proof that the calling thread is attached to the
782    /// interpreter, but this function can be used to call them unsafely.
783    ///
784    /// # Safety
785    ///
786    /// - This token and any borrowed Python references derived from it can only be safely used
787    ///   whilst the currently executing thread is actually attached to the interpreter.
788    /// - This function creates a token with an *unbounded* lifetime. Safe code can assume that
789    ///   holding a [`Python<'py>`] token means the thread is attached and stays attached for the
790    ///   lifetime `'py`. If you let it or borrowed Python references escape to safe code you are
791    ///   responsible for bounding the lifetime `'unbound` appropriately. For more on unbounded
792    ///   lifetimes, see the [nomicon].
793    ///
794    /// [nomicon]: https://doc.rust-lang.org/nomicon/unbounded-lifetimes.html
795    #[inline]
796    pub unsafe fn assume_attached() -> Python<'unbound> {
797        Python(PhantomData, PhantomData)
798    }
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804    use crate::platform::prelude::*;
805    use crate::{
806        internal::state::ForbidAttaching,
807        types::{IntoPyDict, PyList},
808    };
809
810    #[test]
811    fn test_eval() {
812        Python::attach(|py| {
813            // Make sure builtin names are accessible
814            let v: i32 = py
815                .eval(c"min(1, 2)", None, None)
816                .map_err(|e| e.display(py))
817                .unwrap()
818                .extract()
819                .unwrap();
820            assert_eq!(v, 1);
821
822            let d = [("foo", 13)].into_py_dict(py).unwrap();
823
824            // Inject our own global namespace
825            let v: i32 = py
826                .eval(c"foo + 29", Some(&d), None)
827                .unwrap()
828                .extract()
829                .unwrap();
830            assert_eq!(v, 42);
831
832            // Inject our own local namespace
833            let v: i32 = py
834                .eval(c"foo + 29", None, Some(&d))
835                .unwrap()
836                .extract()
837                .unwrap();
838            assert_eq!(v, 42);
839
840            // Make sure builtin names are still accessible when using a local namespace
841            let v: i32 = py
842                .eval(c"min(foo, 2)", None, Some(&d))
843                .unwrap()
844                .extract()
845                .unwrap();
846            assert_eq!(v, 2);
847        });
848    }
849
850    #[test]
851    #[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled
852    fn test_detach_releases_and_acquires_gil() {
853        Python::attach(|py| {
854            let b = alloc::sync::Arc::new(std::sync::Barrier::new(2));
855
856            let b2 = b.clone();
857            std::thread::spawn(move || Python::attach(|_| b2.wait()));
858
859            py.detach(|| {
860                // If `detach` does not release the GIL, this will deadlock because
861                // the thread spawned above will never be able to acquire the GIL.
862                b.wait();
863            });
864
865            unsafe {
866                // If the GIL is not reacquired at the end of `detach`, this call
867                // will crash the Python interpreter.
868                let tstate = ffi::PyEval_SaveThread();
869                ffi::PyEval_RestoreThread(tstate);
870            }
871        });
872    }
873
874    #[test]
875    #[cfg(panic = "unwind")]
876    fn test_detach_panics_safely() {
877        Python::attach(|py| {
878            let result = std::panic::catch_unwind(|| unsafe {
879                let py = Python::assume_attached();
880                py.detach(|| {
881                    panic!("There was a panic!");
882                });
883            });
884
885            // Check panic was caught
886            assert!(result.is_err());
887
888            // If `detach` is implemented correctly, this thread still owns the GIL here
889            // so the following Python calls should not cause crashes.
890            let list = PyList::new(py, [1, 2, 3, 4]).unwrap();
891            assert_eq!(list.extract::<Vec<i32>>().unwrap(), vec![1, 2, 3, 4]);
892        });
893    }
894
895    #[cfg(not(pyo3_disable_reference_pool))]
896    #[test]
897    fn test_detach_pass_stuff_in() {
898        let list = Python::attach(|py| PyList::new(py, vec!["foo", "bar"]).unwrap().unbind());
899        let mut v = vec![1, 2, 3];
900        let a = alloc::sync::Arc::new(String::from("foo"));
901
902        Python::attach(|py| {
903            py.detach(|| {
904                drop((list, &mut v, a));
905            });
906        });
907    }
908
909    #[test]
910    #[cfg(not(Py_LIMITED_API))]
911    fn test_acquire_gil() {
912        use core::ffi::c_int;
913
914        const GIL_NOT_HELD: c_int = 0;
915        const GIL_HELD: c_int = 1;
916
917        // Before starting the interpreter the state of calling `PyGILState_Check`
918        // seems to be undefined, so let's ensure that Python is up.
919        #[cfg(not(any(PyPy, GraalPy)))]
920        Python::initialize();
921
922        let state = unsafe { crate::ffi::PyGILState_Check() };
923        assert_eq!(state, GIL_NOT_HELD);
924
925        Python::attach(|_| {
926            let state = unsafe { crate::ffi::PyGILState_Check() };
927            assert_eq!(state, GIL_HELD);
928        });
929
930        let state = unsafe { crate::ffi::PyGILState_Check() };
931        assert_eq!(state, GIL_NOT_HELD);
932    }
933
934    #[test]
935    fn test_ellipsis() {
936        Python::attach(|py| {
937            assert_eq!(py.Ellipsis().to_string(), "Ellipsis");
938
939            let v = py
940                .eval(c"...", None, None)
941                .map_err(|e| e.display(py))
942                .unwrap();
943
944            assert!(v.eq(py.Ellipsis()).unwrap());
945        });
946    }
947
948    #[test]
949    fn test_py_run_inserts_globals() {
950        use crate::types::dict::PyDictMethods;
951
952        Python::attach(|py| {
953            let namespace = PyDict::new(py);
954            py.run(
955                c"class Foo: pass\na = int(3)",
956                Some(&namespace),
957                Some(&namespace),
958            )
959            .unwrap();
960            assert!(matches!(namespace.get_item("Foo"), Ok(Some(..))));
961            assert!(matches!(namespace.get_item("a"), Ok(Some(..))));
962            // 3.9 and older did not automatically insert __builtins__ if it wasn't inserted "by hand"
963            #[cfg(not(Py_3_10))]
964            assert!(matches!(namespace.get_item("__builtins__"), Ok(Some(..))));
965        })
966    }
967
968    #[cfg(feature = "macros")]
969    #[test]
970    fn test_py_run_inserts_globals_2() {
971        use alloc::ffi::CString;
972
973        #[crate::pyclass(crate = "crate")]
974        #[derive(Clone)]
975        struct CodeRunner {
976            code: CString,
977        }
978
979        impl CodeRunner {
980            fn reproducer(&mut self, py: Python<'_>) -> PyResult<()> {
981                let variables = PyDict::new(py);
982                variables.set_item("cls", crate::Py::new(py, self.clone())?)?;
983
984                py.run(self.code.as_c_str(), Some(&variables), None)?;
985                Ok(())
986            }
987        }
988
989        #[crate::pymethods(crate = "crate")]
990        impl CodeRunner {
991            fn func(&mut self, py: Python<'_>) -> PyResult<()> {
992                py.import("math")?;
993                Ok(())
994            }
995        }
996
997        let mut runner = CodeRunner {
998            code: CString::new(
999                r#"
1000cls.func()
1001"#
1002                .to_string(),
1003            )
1004            .unwrap(),
1005        };
1006
1007        Python::attach(|py| {
1008            runner.reproducer(py).unwrap();
1009        });
1010    }
1011
1012    #[test]
1013    fn python_is_zst() {
1014        assert_eq!(core::mem::size_of::<Python<'_>>(), 0);
1015    }
1016
1017    #[test]
1018    fn test_try_attach_fail_during_gc() {
1019        Python::attach(|_| {
1020            assert!(Python::try_attach(|_| {}).is_some());
1021
1022            let guard = ForbidAttaching::during_traverse();
1023            assert!(Python::try_attach(|_| {}).is_none());
1024            drop(guard);
1025
1026            assert!(Python::try_attach(|_| {}).is_some());
1027        })
1028    }
1029
1030    #[test]
1031    fn test_try_attach_ok_when_detached() {
1032        Python::attach(|py| {
1033            py.detach(|| {
1034                assert!(Python::try_attach(|_| {}).is_some());
1035            });
1036        });
1037    }
1038}