MeshLib
 
Loading...
Searching...
No Matches
MRPython.h
Go to the documentation of this file.
1#pragma once
2
11#include "exports.h"
12#include "MRPybind11.h"
13
14#include "MRMesh/MRExpected.h"
15#include <functional>
16#include <filesystem>
17#include <unordered_map>
18
19#define MR_INIT_PYTHON_MODULE( moduleName ) MR_INIT_PYTHON_MODULE_PRECALL( moduleName, [](){} )
20
21#define MR_INIT_PYTHON_MODULE_PRECALL( moduleName, precall )\
22PYBIND11_MODULE( moduleName, m )\
23{\
24 precall();\
25 auto& adders = MR::PythonExport::instance().functions( #moduleName );\
26 for ( auto& fs : adders )\
27 for ( auto& f : fs )\
28 f( m );\
29}\
30static MR::PythonFunctionAdder moduleName##_init_( #moduleName, &PyInit_##moduleName );
31
32#define MR_ADD_PYTHON_FUNCTION( moduleName , name , func , description ) \
33 static MR::PythonFunctionAdder name##_adder_( #moduleName, [](pybind11::module_& m){ m.def(#name, func, description);} );
34
35#define MR_ADD_PYTHON_CUSTOM_DEF( moduleName , name , ... ) \
36_Pragma("warning(push)") \
37_Pragma("warning(disable:4459)") \
38 static MR::PythonFunctionAdder name##_adder_( #moduleName, __VA_ARGS__ ); \
39_Pragma("warning(pop)")
40
42#define _MR_PYTHON_CUSTOM_CLASS_HOLDER_NAME( name ) name##_class_
43
46#define MR_PYTHON_CUSTOM_CLASS( name ) ( *_MR_PYTHON_CUSTOM_CLASS_HOLDER_NAME( name ) )
47
50#define MR_ADD_PYTHON_CUSTOM_CLASS_DECL( moduleName, name, ... ) \
51static std::optional<pybind11::class_<__VA_ARGS__>> _MR_PYTHON_CUSTOM_CLASS_HOLDER_NAME( name );
52
55#define MR_ADD_PYTHON_CUSTOM_CLASS_INST( moduleName, name ) \
56MR_ADD_PYTHON_CUSTOM_DEF( moduleName, name##_inst_, [] ( pybind11::module_& module ) \
57{ \
58 _MR_PYTHON_CUSTOM_CLASS_HOLDER_NAME( name ).emplace( module, #name ); \
59}, MR::PythonExport::Priority::Declaration )
60
66#define MR_ADD_PYTHON_CUSTOM_CLASS_INST_FUNC( moduleName, name, ... ) \
67MR_ADD_PYTHON_CUSTOM_DEF( moduleName, name##_inst_, [] ( pybind11::module_& module ) \
68{ \
69 _MR_PYTHON_CUSTOM_CLASS_HOLDER_NAME( name ) = __VA_ARGS__ ( module ); \
70}, MR::PythonExport::Priority::Declaration )
71
92#define MR_ADD_PYTHON_CUSTOM_CLASS( moduleName, name, ... ) \
93MR_ADD_PYTHON_CUSTOM_CLASS_DECL( moduleName, name, __VA_ARGS__ ) \
94MR_ADD_PYTHON_CUSTOM_CLASS_INST( moduleName, name )
95
96#define MR_ADD_PYTHON_VEC( moduleName, name, type) \
97PYBIND11_MAKE_OPAQUE( std::vector<type> ) \
98MR_ADD_PYTHON_CUSTOM_CLASS_DECL( moduleName, name, std::vector<type>, std::unique_ptr<std::vector<type>> ) \
99MR_ADD_PYTHON_CUSTOM_CLASS_INST_FUNC( moduleName, name, [] ( pybind11::module_& module ) { return pybind11::bind_vector<std::vector<type>>( module, #name, pybind11::module_local(false) ); } ) \
100MR_ADD_PYTHON_CUSTOM_DEF( moduleName, name, [] ( pybind11::module_& ) \
101{\
102 using vecType = std::vector<type>;\
103 MR_PYTHON_CUSTOM_CLASS( name ).\
104 def( pybind11::init<>() ).\
105 def( pybind11::init<size_t>(), pybind11::arg( "size" ) ).\
106 def( "empty", &vecType::empty ).\
107 def( "size", &vecType::size ).\
108 def( "resize", ( void ( vecType::* )( const vecType::size_type ) )& vecType::resize ).\
109 def( "clear", &vecType::clear ); \
110} )
111
112#define MR_ADD_PYTHON_MAP( moduleName, name, mapType ) \
113PYBIND11_MAKE_OPAQUE( mapType ) \
114MR_ADD_PYTHON_CUSTOM_CLASS_DECL( moduleName, name, mapType, std::unique_ptr<mapType> ) \
115MR_ADD_PYTHON_CUSTOM_CLASS_INST_FUNC( moduleName, name, [] ( pybind11::module_& module ) { return pybind11::bind_map<mapType>( module, #name, pybind11::module_local(false) ); } ) \
116MR_ADD_PYTHON_CUSTOM_DEF( moduleName, name, [] ( pybind11::module_& ) \
117{\
118 MR_PYTHON_CUSTOM_CLASS( name ).\
119 def( pybind11::init<>() ).\
120 def( "size", &mapType::size );\
121} )
122
123#define MR_ADD_PYTHON_EXPECTED( moduleName, name, type, errorType ) \
124using name##_expected_type_ = MR::Expected<type, errorType>; \
125MR_ADD_PYTHON_CUSTOM_CLASS( moduleName, name, name##_expected_type_ ) \
126MR_ADD_PYTHON_CUSTOM_DEF( moduleName, name, [] ( pybind11::module_& ) \
127{\
128 using expectedType = Expected<type,errorType>;\
129 MR_PYTHON_CUSTOM_CLASS( name ).\
130 def( "has_value", []() \
131 { PyErr_WarnEx(PyExc_DeprecationWarning, ".has_value is deprecated. Please use 'try - except ValueError'", 1); \
132 return &expectedType::has_value; \
133 }).\
134 def( "value", []() \
135 { \
136 PyErr_WarnEx(PyExc_DeprecationWarning, ".value is deprecated. Please use 'try - except ValueError'", 1); \
137 return ( type& ( expectedType::* )( )& )& expectedType::value; \
138 }, pybind11::return_value_policy::reference_internal ).\
139 def( "error", []() \
140 { \
141 PyErr_WarnEx(PyExc_DeprecationWarning, ".error is deprecated. Please use 'try - except ValueError'", 1); \
142 return ( const errorType& ( expectedType::* )( )const& )& expectedType::error; \
143 } );\
144} )
145
151
152template<StreamType T>
154{
155public:
156 MRPYTHON_API void write( const std::string& text );
157 void flush() {}
158 MRPYTHON_API static int getNumWritten();
159};
160
163
164namespace MR
165{
166
168{
169public:
170 MRPYTHON_API static PythonExport& instance();
171
172 using PythonRegisterFuncton = std::function<void( pybind11::module_& m )>;
173
174 enum class Priority
175 {
178 Count,
179 };
180
182 {
183 PyObject* ( *initFncPointer )( void );
184 std::array<std::vector<PythonRegisterFuncton>, size_t( Priority::Count )> functions;
185 };
186
187 void addFunc( const std::string& moduleName, PythonRegisterFuncton func, Priority priority )
188 {
189 auto& mod = moduleData_[moduleName];
190 mod.functions[size_t( priority )].push_back( func );
191 }
192 void setInitFuncPtr( const std::string& moduleName, PyObject* ( *initFncPointer )( void ) )
193 {
194 auto& mod = moduleData_[moduleName];
195 mod.initFncPointer = initFncPointer;
196 }
197 const std::array<std::vector<PythonRegisterFuncton>, size_t( Priority::Count )>& functions( const std::string& moduleName ) const
198 {
199 auto it = moduleData_.find( moduleName );
200 const static std::array<std::vector<PythonRegisterFuncton>, size_t( Priority::Count )> empty;
201 if ( it == moduleData_.end() )
202 return empty;
203 return it->second.functions;
204 }
205
206 const std::unordered_map<std::string, ModuleData>& modules() const
207 {
208 return moduleData_;
209 }
210private:
211 PythonExport() = default;
212 ~PythonExport() = default;
213
214 std::unordered_map<std::string, ModuleData> moduleData_;
215};
216
218{
219 MRPYTHON_API PythonFunctionAdder( const std::string& moduleName, std::function<void( pybind11::module_& m )> func, PythonExport::Priority priority = PythonExport::Priority::Implementation );
220 MRPYTHON_API PythonFunctionAdder( const std::string& moduleName, PyObject* ( *initFncPointer )( void ) );
221};
222
223// overload `toString` functoion to throw exception from custom `Expected::error` type
224template<typename E>
226{
227 if constexpr (std::is_nothrow_convertible<E, std::string>::value)
228 throw std::runtime_error(err);
229 else
230 throw std::runtime_error(toString(err));
231}
232
233template<typename R, typename E, typename... Args>
234auto decorateExpected( std::function<Expected<R, E>( Args... )>&& f ) -> std::function<R( Args... )>
235{
236 return[fLocal = std::move( f )]( Args&&... args ) mutable -> R
237 {
238 auto res = fLocal(std::forward<Args>( args )...);
239 if (!res.has_value())
240 throwExceptionFromExpected(res.error());
241
242 if constexpr (std::is_void<R>::value)
243 return;
244 else
245 return res.value();
246 };
247}
248
249template<typename F>
250auto decorateExpected( F&& f )
251{
252 return decorateExpected( std::function( std::forward<F>( f ) ) );
253}
254
255template<typename R, typename T, typename... Args>
256auto decorateExpected( R( T::* memFunction )( Args... ) )
257{
258 return decorateExpected( std::function<R( T*, Args... )>( std::mem_fn( memFunction ) ) );
259}
260
261}
StreamType
Definition MRPython.h:147
@ Stderr
Definition MRPython.h:149
@ Stdout
Definition MRPython.h:148
Definition MRPython.h:168
std::function< void(pybind11::module_ &m)> PythonRegisterFuncton
Definition MRPython.h:172
void setInitFuncPtr(const std::string &moduleName, PyObject *(*initFncPointer)(void))
Definition MRPython.h:192
const std::array< std::vector< PythonRegisterFuncton >, size_t(Priority::Count)> & functions(const std::string &moduleName) const
Definition MRPython.h:197
Priority
Definition MRPython.h:175
void addFunc(const std::string &moduleName, PythonRegisterFuncton func, Priority priority)
Definition MRPython.h:187
const std::unordered_map< std::string, ModuleData > & modules() const
Definition MRPython.h:206
static MRPYTHON_API PythonExport & instance()
Definition MRPython.h:154
static MRPYTHON_API int getNumWritten()
void flush()
Definition MRPython.h:157
MRPYTHON_API void write(const std::string &text)
Definition MRCameraOrientationPlugin.h:8
void throwExceptionFromExpected(const E &err)
Definition MRPython.h:225
tl::expected< T, E > Expected
Definition MRExpected.h:58
auto decorateExpected(std::function< Expected< R, E >(Args...)> &&f) -> std::function< R(Args...)>
Definition MRPython.h:234
MRMESH_API std::string_view toString(DimensionsVisualizePropertyType value)
Definition MRPython.h:182
std::array< std::vector< PythonRegisterFuncton >, size_t(Priority::Count)> functions
Definition MRPython.h:184
Definition MRPython.h:218
MRPYTHON_API PythonFunctionAdder(const std::string &moduleName, PyObject *(*initFncPointer)(void))
MRPYTHON_API PythonFunctionAdder(const std::string &moduleName, std::function< void(pybind11::module_ &m)> func, PythonExport::Priority priority=PythonExport::Priority::Implementation)