Line data Source code
1 : // SPDX-License-Identifier: BSD-3-Clause 2 : // Copyright (c) 2023 Scipp contributors (https://github.com/scipp) 3 : /// @file 4 : /// @author Simon Heybrock 5 : #pragma once 6 : 7 : #include "scipp/core/dtype.h" 8 : 9 : #include "pybind11.h" 10 : 11 : namespace py = pybind11; 12 : 13 : namespace scipp::python { 14 : 15 : /// Wrapper around pybind11::object to provide deep copy and deep comparison. 16 : /// 17 : /// Whenever this class makes calls to Python it acquires the GIL first to 18 : /// ensure that it can be used as part of code that has a released GIL. Since 19 : /// this class is meant as an element type in Variable, this is often the case, 20 : /// e.g., in any operation that makes copies of variables. 21 : class PyObject { 22 : public: 23 39935 : PyObject() = default; 24 0 : PyObject(PyObject &&other) = default; 25 73 : PyObject &operator=(PyObject &&other) = default; 26 43 : PyObject(const PyObject &other) : PyObject(other.m_object) {} 27 43 : PyObject &operator=(const PyObject &other) { return *this = PyObject(other); } 28 : ~PyObject(); 29 : 30 : PyObject(const py::object &object); 31 : 32 71 : const py::object &to_pybind() const noexcept { return m_object; } 33 39 : py::object &to_pybind() noexcept { return m_object; } 34 : 35 : bool operator==(const PyObject &other) const; 36 : 37 : private: 38 : py::object m_object; 39 : }; 40 : 41 : [[nodiscard]] PyObject copy(const PyObject &obj); 42 : 43 : std::ostream &operator<<(std::ostream &os, const PyObject &obj); 44 : std::string to_string(const PyObject &obj); 45 : 46 : } // namespace scipp::python 47 : 48 : namespace scipp::core { 49 : template <> inline constexpr DType dtype<python::PyObject>{3000}; 50 : } // namespace scipp::core