### Check Guide Links Source: https://pyo3.rs/main/contributing Installs lychee and uses the check-guide session to validate all links within the user guide. ```bash nox -s check-guide ``` -------------------------------- ### Build User Guide Locally Source: https://pyo3.rs/main/contributing Installs mdbook, mdbook-tabs, and nox to build and preview the user guide locally. ```bash nox -s build-guide -- --open ``` -------------------------------- ### All-in-One Script for PyO3 Project Setup Source: https://pyo3.rs/main/index.html This bash script automates the entire process of creating a PyO3 Python package: creating a directory, setting up a virtual environment, installing maturin, initializing the project, and building it for development. ```bash mkdir string_sum && cd "$_" python -m venv .env source .env/bin/activate pip install maturin maturin init --bindings pyo3 maturin develop ``` -------------------------------- ### Install and Develop Python Module with Maturin Source: https://pyo3.rs/main/doc Steps to install `maturin` and build/develop a Python module created with PyO3. Assumes a virtual environment is set up. ```bash cd string_sum python -m venv .env source .env/bin/activate pip install maturin maturin develop ``` -------------------------------- ### Install and Run LLVM Coverage Tool Source: https://pyo3.rs/main/contributing Install the `cargo-llvm-cov` plugin and run it to check code coverage. This is a prerequisite for generating coverage reports. ```bash cargo install cargo-llvm-cov ``` ```bash cargo llvm-cov ``` -------------------------------- ### Installing and Using Maturin Source: https://pyo3.rs/main/doc/pyo3 Demonstrates the command-line steps to install the 'maturin' build tool and then build and test a Rust-based Python module. This is a common workflow for developing PyO3 extensions. ```Shell cd string_sum python -m venv .env source .env/bin/activate pip install maturin maturin develop python >>> import string_sum >>> string_sum.sum_as_string(5, 20) '25' ``` -------------------------------- ### Install Nightly Rust Toolchain and Components Source: https://pyo3.rs/main/debugging Install the nightly Rust toolchain and the rust-src component, which is required for compiling the Rust standard library. ```bash rustup install nightly rustup override set nightly rustup component add rust-src ``` -------------------------------- ### Install and Build Python Module with Maturin Source: https://pyo3.rs/main/doc/pyo3?search= Commands to set up a Python virtual environment, install `maturin`, and build/develop a Rust-based Python module. ```bash $ cd string_sum $ python -m venv .env $ source .env/bin/activate $ pip install maturin $ maturin develop # lots of progress output as maturin runs the compilation... $ python >>> import string_sum >>> string_sum.sum_as_string(5, 20) '25' ``` -------------------------------- ### Py_GetPrefix Source: https://pyo3.rs/main/doc/pyo3/ffi Gets the Python installation prefix (Deprecated). ```APIDOC ## Py_GetPrefix ### Description Gets the Python installation prefix (Deprecated). ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Install maturin with pyenv Source: https://pyo3.rs/main/getting-started Activates a pyenv virtual environment and installs maturin within it. ```bash pyenv activate pyo3 pip install maturin ``` -------------------------------- ### Install Python Development Headers on Ubuntu Source: https://pyo3.rs/main/doc/pyo3?search= Command to install the Python development headers, which are necessary for building Python extensions on Ubuntu. ```bash sudo apt install python3-dev ``` -------------------------------- ### Installing Maturin with Pip Source: https://pyo3.rs/main/doc/pyo3_ffi/index.html This sequence of commands shows how to set up a Python virtual environment and install the `maturin` build tool using pip. This is a prerequisite for building Rust-based Python packages. ```bash $ cd string_sum $ python -m venv .env $ source .env/bin/activate $ pip install maturin ``` -------------------------------- ### Install rust-src component Source: https://pyo3.rs/main/contributing Install the `rust-src` component for Rust UI tests. This is necessary for the UI test output to match PyO3's CI environment. ```shell rustup component add rust-src ``` -------------------------------- ### Install nox Source: https://pyo3.rs/main/contributing Install nox globally using pip or pipx. pipx is recommended for managing Python applications. ```shell pip install nox ``` ```shell pip install pipx pipx install nox ``` -------------------------------- ### Install maturin with pip Source: https://pyo3.rs/main/getting-started Installs the maturin build tool for system Python using pip. ```bash pip install maturin --user ``` -------------------------------- ### Install Python with pyenv Source: https://pyo3.rs/main/getting-started Installs a specific Python version using pyenv and keeps the source files for debugging. ```bash pyenv install 3.12 --keep ``` -------------------------------- ### Install Nightly Rust Toolchain and Components Source: https://pyo3.rs/main/print Installs the nightly Rust toolchain, sets it as the override, and adds the rust-src component, which is necessary for compiling the Rust standard library with ThreadSanitizer. ```bash rustup install nightly rustup override set nightly rustup component add rust-src ``` -------------------------------- ### Installing and Using PyO3 Module with Maturin Source: https://pyo3.rs/main/doc/pyo3/index.html Demonstrates the steps to install the 'maturin' build tool, build a PyO3 Rust module, and then use it in a Python interpreter. This is a common workflow for developing Python extensions with Rust. ```Shell $ cd string_sum $ python -m venv .env $ source .env/bin/activate $ pip install maturin ``` ```Shell $ maturin develop # lots of progress output as maturin runs the compilation... $ python >>> import string_sum >>> string_sum.sum_as_string(5, 20) '25' ``` -------------------------------- ### Py_GetBuildInfo Source: https://pyo3.rs/main/doc/pyo3/ffi Gets information about the Python build. ```APIDOC ## Py_GetBuildInfo ### Description Gets information about the Python build. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Py_InitializeEx Source: https://pyo3.rs/main/doc/pyo3/ffi Initializes the Python interpreter with optional sitecustomize. ```APIDOC ## Py_InitializeEx ### Description Initializes the Python interpreter with optional sitecustomize. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Build and open PyO3 documentation Source: https://pyo3.rs/main/contributing Build the PyO3 documentation, including all features, and open it in a browser. Ensure nox is installed. ```shell nox -s docs -- open ``` -------------------------------- ### Get Pointer to Specific Item Source: https://pyo3.rs/main/doc/pyo3/buffer/struct.pyuntypedbuffer Gets a raw pointer to a specific item within the buffer using an array of indices. If indices are incomplete, it returns the start address of a sub-array. ```rust pub fn get_ptr(&self, indices: &[usize]) -> *mut c_void ``` -------------------------------- ### Get Pointer to Buffer Start Source: https://pyo3.rs/main/doc/pyo3/buffer/struct.pyuntypedbuffer Retrieves a raw pointer to the beginning of the buffer's memory. Use with caution, as the memory can be mutated by other code. ```rust pub fn buf_ptr(&self) -> *mut c_void ``` -------------------------------- ### Setup for PyO3 anyhow Integration Source: https://pyo3.rs/main/doc/pyo3/anyhow/index.html Add `anyhow` and enable the `anyhow` feature for `pyo3` in your `Cargo.toml`. Ensure compatible versions are used. ```toml [dependencies] ## change * to the version you want to use, ideally the latest. anyhow = "*" pyo3 = { version = "0.29.0", features = ["anyhow"] } ``` -------------------------------- ### Handling File Metadata Operations with `and_then` Source: https://pyo3.rs/main/doc/pyo3/type.pyresult Shows how to use `and_then` to chain operations that might fail, like getting file metadata. Includes examples for success and failure cases. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://pyo3.rs/main/index.html These commands set up a new directory, create a Python virtual environment, and activate it. Then, they install the 'maturin' package using pip. ```bash mkdir string_sum cd string_sum python -m venv .env source .env/bin/activate pip install maturin ``` -------------------------------- ### pub fn initialize() Source: https://pyo3.rs/main/doc/pyo3/marker/struct.python Prepares the use of Python by initializing the interpreter if it's not already running. If initialized, it disables signal handling and does not support embedding under PyPy. ```APIDOC ## pub fn initialize() ### Description Prepares the use of Python. If the Python interpreter is not already initialized, this function will initialize it with signal handling disabled. If the Python interpreter is already initialized, this function has no effect. This function is unavailable under PyPy. ### Examples ```rust use pyo3::prelude::* Python::initialize(); Python::attach(|py| py.run(c"print('Hello World')", None, None)) ``` ``` -------------------------------- ### Get Tuple Item by Index Source: https://pyo3.rs/main/doc/pyo3/types/trait.pytuplemethods Retrieves an item from a Python tuple at a specific index. This example demonstrates how to extract an integer from a tuple created in Rust. Ensure the index is within bounds to avoid errors. ```rust use pyo3::prelude::*; Python::attach(|py| -> PyResult<()> { let tuple = (1, 2, 3).into_pyobject(py)?; let obj = tuple.get_item(0)?; assert_eq!(obj.extract::()?, 1); Ok(()) }) ``` -------------------------------- ### Initialize New PyO3 Project with Maturin Source: https://pyo3.rs/main/print Initialize a new PyO3 project using the Maturin command-line tool. ```bash maturin init ``` -------------------------------- ### All-in-One PyO3 Project Setup Script Source: https://pyo3.rs/main/print This bash script automates the entire process of creating, initializing, building, and developing a PyO3 Python package. Replace 'string_sum' with your desired package name. ```bash mkdir string_sum && cd "$ירת" python -m venv .env source .env/bin/activate pip install maturin maturin init --bindings pyo3 maturin develop ``` -------------------------------- ### Get Item from Python Mapping Source: https://pyo3.rs/main/doc/pyo3/struct.bound Gets an item from a Python mapping using its key. ```rust fn get_item(&self, key: K) -> PyResult> where K: IntoPyObject<'py>, ``` -------------------------------- ### Install maturin with pipx Source: https://pyo3.rs/main/getting-started Installs the maturin build tool in an isolated environment using pipx. ```bash pipx install maturin ``` -------------------------------- ### Handle System Signals with Python Source: https://pyo3.rs/main/print This example shows how to configure Python's signal handling within a Rust application. It demonstrates setting a specific signal (SIGINT) to its default action using the `signal` module. ```rust use pyo3::prelude::*; fn main() -> PyResult<()> { Python::attach(|py| -> PyResult<()> { let signal = py.import("signal")?; signal .getattr("signal")? .call1((signal.getattr("SIGINT")?, signal.getattr("SIG_DFL")?))?; Ok(()) }) } ``` -------------------------------- ### Readonly Property with Get Source: https://pyo3.rs/main/print Use #[pyo3(get)] to expose a field as a readonly Python property. ```rust use pyo3::prelude::*; #[allow(dead_code)] #[pyclass] struct MyClass { #[pyo3(get)] num: i32, } ``` -------------------------------- ### Using `PyTuple::new` after `gil-refs` removal Source: https://pyo3.rs/main/migration Shows the updated syntax for creating a `PyTuple` using `PyTuple::new` after the `gil-refs` feature was removed and the Bound API was favored. ```Rust use pyo3::prelude::*; use pyo3::types::PyTuple; fn main() { Python::attach(|py| { // For example, for PyTuple. Many such APIs have been changed. let tup = PyTuple::new(py, [1, 2, 3]); }) ``` -------------------------------- ### Create PyO3 project with pyenv and maturin Source: https://pyo3.rs/main/getting-started Sets up a new project directory, creates a pyenv virtual environment, and initializes it with maturin. ```bash mkdir pyo3-example cd pyo3-example pyenv virtualenv pyo3 pyenv local pyo3 pip install maturin maturin init ``` -------------------------------- ### Install Maturin Build Manager Source: https://pyo3.rs/main/print Install the Maturin build manager within your activated virtual environment using pip. ```bash pip install maturin ``` -------------------------------- ### Python Package Initialization for PyO3 Bindings Source: https://pyo3.rs/main/python-typing-hints This `__init__.py` content allows importing all exposed elements from the extension module directly from the package, treating the folder as a package. ```python from .my_project import * ``` -------------------------------- ### Py_GetBuildInfo Source: https://pyo3.rs/main/doc/pyo3_ffi/index.html Returns a string describing the Python build configuration. This FFI function provides build information. ```APIDOC ## Py_GetBuildInfo ### Description Returns a string describing the Python build configuration. This FFI function provides build information. ### Method FFI Call ### Endpoint N/A ### Parameters None explicitly documented in source. ### Request Example N/A ### Response None explicitly documented in source. #### Success Response (200) None explicitly documented in source. #### Response Example None explicitly documented in source. ``` -------------------------------- ### Install Python 3.12 with pyenv Source: https://pyo3.rs/main/print This command installs a specific Python version using pyenv, keeping the source files for potential debugging. ```bash pyenv install 3.12 --keep ``` -------------------------------- ### Create PyO3 project with maturin new Source: https://pyo3.rs/main/getting-started Creates a new PyO3 project using `maturin new`, sets up the pyenv environment, and navigates into the project directory. ```bash maturin new -b pyo3 pyo3-example cd pyo3-example pyenv virtualenv pyo3 pyenv local pyo3 ``` -------------------------------- ### Get List Item Unchecked Source: https://pyo3.rs/main/doc/pyo3/struct.bound Gets a list item at a specified index without bounds checking or synchronization. Undefined behavior if the index is out of bounds. ```rust unsafe fn get_item_unchecked(&self, index: usize) -> Bound<'py, PyAny> ``` -------------------------------- ### Run PyO3 Benchmarks Source: https://pyo3.rs/main/contributing Execute the Rust-based benchmarks for PyO3. Ensure you are in the `pyo3-benches` directory. ```bash nox -s bench ``` -------------------------------- ### Getting the positive value of a Python object Source: https://pyo3.rs/main/doc/pyo3/prelude/trait.pyanymethods Use the `pos` method to get the positive value of a Python object. This is equivalent to the unary `+` operator in Python. ```rust pub trait PyAnyMethods<'py>: Sealed { fn pos(&self) -> PyResult>; // ... other methods } ``` -------------------------------- ### Setup for Chrono Conversions Source: https://pyo3.rs/main/doc/pyo3/chrono/index.html Add these dependencies to your Cargo.toml to enable chrono conversions. Ensure compatible versions of chrono and PyO3 are used. ```toml [dependencies] chrono = "0.4" pyo3 = { version = "0.29.0", features = ["chrono"] } ``` -------------------------------- ### Install Maturin with Pip Source: https://pyo3.rs/main/doc/src/pyo3/lib.rs Install the maturin build tool using pip within a Python virtual environment. This is a prerequisite for building Python extensions with Rust. ```bash cd string_sum python -m venv .env source .env/bin/activate pip install maturin ``` -------------------------------- ### Basic Module Creation with #[pymodule] Source: https://pyo3.rs/main/module Demonstrates how to create a basic Python module named 'my_extension' with a 'double' function using the #[pymodule] and #[pyfunction] macros. ```APIDOC ## Creating a Module Use `#[pymodule]` to create a module. The module name defaults to the Rust module name. You can override it with `#[pyo3(name = "custom_name")]`. ### Example: Basic Module ```rust #[pymodule] mod my_extension { use pyo3::prelude::*; #[pyfunction] fn double(x: usize) -> usize { x * 2 } #[pymodule_export] use super::double; // Makes the double function available to Python } ``` ### Example: Custom Module Name ```rust #[pymodule(name = "custom_name")] mod my_extension { use pyo3::prelude::*; #[pyfunction] fn double(x: usize) -> usize { x * 2 } #[pymodule_export] use super::double; } ``` **Note:** The module name must match the shared library file name (e.g., `my_extension.so` or `my_extension.pyd`) to avoid `ImportError`. ``` -------------------------------- ### Py_Main Source: https://pyo3.rs/main/doc/pyo3_ffi/index.html Initializes the Python interpreter and runs it as a command-line script. This FFI function is for running Python scripts. ```APIDOC ## Py_Main ### Description Initializes the Python interpreter and runs it as a command-line script. This FFI function is for running Python scripts. ### Method FFI Call ### Endpoint N/A ### Parameters None explicitly documented in source. ### Request Example N/A ### Response None explicitly documented in source. #### Success Response (200) None explicitly documented in source. #### Response Example None explicitly documented in source. ``` -------------------------------- ### Getting the string representation of a Python object Source: https://pyo3.rs/main/doc/pyo3/prelude/trait.pyanymethods Use the `repr` method to get the official string representation of a Python object, equivalent to `repr(obj)` in Python. ```rust pub trait PyAnyMethods<'py>: Sealed { fn repr(&self) -> PyResult>; } ``` -------------------------------- ### Build and Test PyO3 Package Source: https://pyo3.rs/main/print Run 'maturin develop' to build the package and install it into the Python virtualenv. Then, launch Python to import and test the 'sum_as_string' function. ```bash maturin develop # lots of progress output as maturin runs the compilation... python >>> import string_sum >>> string_sum.sum_as_string(5, 20) '25' ``` -------------------------------- ### Python Example Causing RuntimeError Source: https://pyo3.rs/main/print An example of Python code that triggers a `RuntimeError` due to exclusive borrowing issues when using a decorator with a `&mut self` receiver. ```python @Counter def say_hello(): if say_hello.count < 2: print(f"hello from decorator") say_hello() # RuntimeError: Already borrowed ``` -------------------------------- ### Create New PyO3 Project with Maturin (Alternative) Source: https://pyo3.rs/main/print Create a new PyO3 project directly using 'maturin new', specifying the 'pyo3' build backend and project name. This is an alternative to 'maturin init'. ```bash maturin new -b pyo3 pyo3-example cd pyo3-example pyenv virtualenv pyo3 pyenv local pyo3 ``` -------------------------------- ### Python Platform Tag Example Source: https://pyo3.rs/main/building-and-distribution This example shows the platform tag appended to a shared library extension for CPython 3.10 on macOS, indicating interpreter compatibility. ```text # CPython 3.10 on macOS .cpython-310-darwin.so ``` -------------------------------- ### Instantiate and Print Rust Class Instance in Python Source: https://pyo3.rs/main/class/object Demonstrates importing a Rust-defined class in Python and creating an instance. The default representation is shown. ```python from my_module import Number n = Number(5) print(n) ``` -------------------------------- ### Create Project Folder and Virtual Environment Source: https://pyo3.rs/main/print Use pyenv to create a new project directory and set up a dedicated virtual environment for your PyO3 project. ```bash mkdir pyo3-example cd pyo3-example pyenv virtualenv pyo3 pyenv local pyo3 ``` -------------------------------- ### Python Example Causing RuntimeError with Mutable Borrow Source: https://pyo3.rs/main/class/call An example demonstrating a RuntimeError when a decorated function recursively calls itself, due to exclusive borrowing issues in PyO3. ```python @Counter def say_hello(): if say_hello.count < 2: print(f"hello from decorator") say_hello() # RuntimeError: Already borrowed ``` -------------------------------- ### Getting Mutable References from Result Source: https://pyo3.rs/main/doc/pyo3/prelude/type.pyresult Shows how to use `as_mut` to get mutable references to the contained values of a `Result`. This allows in-place modification of `Ok` or `Err` values. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Launch rust-lldb with Python Interpreter Source: https://pyo3.rs/main/debugging Start `rust-lldb` and attach it to the Python interpreter. This is the initial step for setting breakpoints and debugging your Rust code within a Python environment. ```bash rust-lldb -- python ``` -------------------------------- ### Python List Manipulation Example Source: https://pyo3.rs/main/types This Rust code demonstrates how to create a Python list, append an item, create a new reference to the list, and release the original reference, mirroring the provided Python example. ```rust use pyo3::prelude::*; use pyo3::types::PyList; fn example<'py>(py: Python<'py>) -> PyResult<()> { let x: Bound<'py, PyList> = PyList::empty(py); x.append(1)?; let y: Bound<'py, PyList> = x.clone(); // y is a new reference to the same list drop(x); // release the original reference x Ok(()) } Python::attach(example).unwrap(); ``` ```rust use pyo3::prelude::*; use pyo3::types::PyList; fn example(py: Python<'_>) -> PyResult<()> { let x = PyList::empty(py); x.append(1)?; let y = x.clone(); drop(x); Ok(()) } Python::attach(example).unwrap(); ``` -------------------------------- ### Py_Initialize Source: https://pyo3.rs/main/doc/pyo3/ffi Initializes the Python interpreter. ```APIDOC ## Py_Initialize ### Description Initializes the Python interpreter. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Py_GetConstant Source: https://pyo3.rs/main/doc/pyo3/ffi Gets a built-in constant. ```APIDOC ## Py_GetConstant ### Description Gets a built-in constant. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Py_InitializeFromConfig Source: https://pyo3.rs/main/doc/pyo3/ffi Initializes the Python interpreter from a configuration. ```APIDOC ## Py_InitializeFromConfig ### Description Initializes the Python interpreter from a configuration. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Load Python File at Runtime Source: https://pyo3.rs/main/print This example shows how to load Python script content at runtime using `std::fs::read_to_string`. It ensures that Python's `sys.path` is correctly configured to resolve module dependencies before executing a function. ```rust use pyo3::prelude::*; use pyo3::types::PyList; use std::fs; use std::path::Path; use std::ffi::CString; fn main() -> PyResult<()> { let path = Path::new("/usr/share/python_app"); let py_app = CString::new(fs::read_to_string(path.join("app.py"))?)?; let from_python = Python::attach(|py| -> PyResult> { let syspath = py .import("sys")? .getattr("path")? .cast_into::()?; syspath.insert(0, path)?; let app: Py = PyModule::from_code(py, py_app.as_c_str(), c"app.py", c"")? .getattr("run")? .into(); app.call0(py) }); println!("py: {}", from_python?); Ok(()) } ``` -------------------------------- ### Py_GETENV Source: https://pyo3.rs/main/doc/pyo3/ffi Gets an environment variable. ```APIDOC ## Py_GETENV ### Description Gets an environment variable. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Py_PreInitializeFromArgs Source: https://pyo3.rs/main/doc/pyo3/ffi Pre-initializes the Python interpreter with arguments. ```APIDOC ## Py_PreInitializeFromArgs ### Description Pre-initializes the Python interpreter with arguments. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Handling Arguments in Subclass Constructors Source: https://pyo3.rs/main/print Demonstrates how to accept `*args` and `**kwargs` in a subclass's `#[new]` method to pass arguments to the base class constructor, enabling instantiation with initial items. ```rust use pyo3::prelude::*; use pyo3::types::PyDict; #[pyclass(extends=PyDict)] struct MyDict { private: i32, } #[pymethods] impl MyDict { #[new] #[pyo3(signature = (*args, **kwargs))] fn new(args: &Bound<'_, PyAny>, kwargs: Option<&Bound<'_, PyAny>>) -> Self { Self { private: 0 } } // some custom methods that use `private` here... } Python::attach(|py| { let cls = py.get_type::(); pyo3::py_run!(py, cls, "cls(a=1, b=2)") }); ``` -------------------------------- ### Simple Field Properties with #[pyo3(get, set)] Source: https://pyo3.rs/main/class Use `#[pyo3(get, set)]` on struct fields for direct read/write access without side effects. The field type must implement `IntoPyObject` and `FromPyObject` traits. ```rust use pyo3::prelude::*; #[allow(dead_code)] #[pyclass] struct MyClass { #[pyo3(get, set)] num: i32, } ```