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