Skip to main content

rigetti_pyo3/
traits.rs

1// Copyright 2022 Rigetti Computing
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Macros for implementing "dunder" methods based on traits.
16
17#[cfg(not(feature = "stubs"))]
18/// Implement `__repr__` for a type that implement [`Debug`](std::fmt::Debug).
19#[macro_export]
20macro_rules! impl_repr {
21    ($name: ident) => {
22        #[$crate::pyo3::pymethods]
23        impl $name {
24            /// Implements `__repr__` for Python in terms of the Rust
25            /// [`Debug`](std::fmt::Debug) implementation.
26            pub fn __repr__(&self) -> String {
27                format!("{self:?}")
28            }
29        }
30    };
31}
32
33#[cfg(feature = "stubs")]
34/// Implement `__repr__` for a type that implement [`Debug`](std::fmt::Debug).
35#[macro_export]
36macro_rules! impl_repr {
37    ($name: ident) => {
38        #[cfg_attr(feature = "stubs", $crate::pyo3_stub_gen::derive::gen_stub_pymethods)]
39        #[$crate::pyo3::pymethods]
40        impl $name {
41            /// Implements `__repr__` for Python in terms of the Rust
42            /// [`Debug`](std::fmt::Debug) implementation.
43            pub fn __repr__(&self) -> String {
44                format!("{self:?}")
45            }
46        }
47    };
48}