Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
Pythonize.cxx
Go to the documentation of this file.
1// Bindings
2#include "CPyCppyy.h"
3#include "Pythonize.h"
4#include "Converters.h"
5#include "CPPInstance.h"
6#include "CPPFunction.h"
7#include "CPPOverload.h"
8#include "CustomPyTypes.h"
9#include "LowLevelViews.h"
10#include "ProxyWrappers.h"
11#include "PyCallable.h"
12#include "PyStrings.h"
13#include "TypeManip.h"
14#include "Utility.h"
15
16// Standard
17#include <algorithm>
18#include <complex>
19#include <set>
20#include <stdexcept>
21#include <sstream>
22#include <string>
23#include <utility>
24
25
26//- data and local helpers ---------------------------------------------------
27namespace CPyCppyy {
28 extern PyObject* gThisModule;
29 std::map<std::string, std::vector<PyObject*>> &pythonizations();
30}
31
32namespace {
33
34// for convenience
35using namespace CPyCppyy;
36
37//-----------------------------------------------------------------------------
39// prevents calls to Py_TYPE(pyclass)->tp_getattr, which is unnecessary for our
40// purposes here and could tickle problems w/ spurious lookups into ROOT meta
42 if (dct) {
45 if (attr) {
48 return ret;
49 }
50 }
52 return false;
53}
54
56// get an attribute without causing getattr lookups
58 if (dct) {
61 return attr;
62 }
63 return nullptr;
64}
65
66//-----------------------------------------------------------------------------
67inline bool IsTemplatedSTLClass(const std::string& name, const std::string& klass) {
68// Scan the name of the class and determine whether it is a template instantiation.
69 auto pos = name.find(klass);
70 return (pos == 0 || pos == 5) && name.find("::", name.rfind(">")) == std::string::npos;
71}
72
73// to prevent compiler warnings about const char* -> char*
74inline PyObject* CallPyObjMethod(PyObject* obj, const char* meth)
75{
76// Helper; call method with signature: obj->meth().
77 Py_INCREF(obj);
78 PyObject* result = PyObject_CallMethod(obj, const_cast<char*>(meth), const_cast<char*>(""));
79 Py_DECREF(obj);
80 return result;
81}
82
83//-----------------------------------------------------------------------------
84inline PyObject* CallPyObjMethod(PyObject* obj, const char* meth, PyObject* arg1)
85{
86// Helper; call method with signature: obj->meth(arg1).
87 Py_INCREF(obj);
89 obj, const_cast<char*>(meth), const_cast<char*>("O"), arg1);
90 Py_DECREF(obj);
91 return result;
92}
93
94//-----------------------------------------------------------------------------
96{
97// Helper; converts python index into straight C index.
99 if (idx == (Py_ssize_t)-1 && PyErr_Occurred())
100 return nullptr;
101
103 if (idx >= size || (idx < 0 && idx < -size)) {
104 PyErr_SetString(PyExc_IndexError, "index out of range");
105 return nullptr;
106 }
107
108 PyObject* pyindex = nullptr;
109 if (idx >= 0) {
111 pyindex = index;
112 } else
114
115 return pyindex;
116}
117
118//-----------------------------------------------------------------------------
119inline bool AdjustSlice(const Py_ssize_t nlen, Py_ssize_t& start, Py_ssize_t& stop, Py_ssize_t& step)
120{
121// Helper; modify slice range to match the container.
122 if ((step > 0 && stop <= start) || (step < 0 && start <= stop))
123 return false;
124
125 if (start < 0) start = 0;
126 if (start >= nlen) start = nlen-1;
127 if (step >= nlen) step = nlen;
128
129 stop = step > 0 ? std::min(nlen, stop) : (stop >= 0 ? stop : -1);
130 return true;
131}
132
133//-----------------------------------------------------------------------------
135{
136// Helper; call method with signature: meth(pyindex).
139 if (!pyindex) {
141 return nullptr;
142 }
143
147 return result;
148}
149
150//- "smart pointer" behavior ---------------------------------------------------
152{
154 PyErr_SetString(PyExc_TypeError, "getattr(): attribute name must be string");
155
157 if (!pyptr)
158 return nullptr;
159
160// prevent a potential infinite loop
161 if (Py_TYPE(pyptr) == Py_TYPE(self)) {
164 PyErr_Format(PyExc_AttributeError, "%s object has no attribute \'%s\'",
168
170 return nullptr;
171 }
172
175 return result;
176}
177
179{
180// Follow operator*() if present (available in python as __deref__), so that
181// smart pointers behave as expected.
183 // TODO: these calls come from TemplateProxy and are unlikely to be needed in practice,
184 // whereas as-is, they can accidentally dereference the result of end() on some STL
185 // containers. Obviously, this is a dumb hack that should be resolved more fundamentally.
187 return nullptr;
188 }
189
190
192}
193
194//-----------------------------------------------------------------------------
196{
197// Follow operator->() if present (available in python as __follow__), so that
198// smart pointers behave as expected.
200}
201
202//- pointer checking bool converter -------------------------------------------
204{
205 if (!CPPInstance_Check(self)) {
206 PyErr_SetString(PyExc_TypeError, "C++ object proxy expected");
207 return nullptr;
208 }
209
210 if (!((CPPInstance*)self)->GetObject())
212
214}
215
216//- vector behavior as primitives ----------------------------------------------
217#if PY_VERSION_HEX < 0x03040000
218#define PyObject_LengthHint _PyObject_LengthHint
219#endif
220
221// TODO: can probably use the below getters in the InitializerListConverter
222struct ItemGetter {
223 ItemGetter(PyObject* pyobj) : fPyObject(pyobj) { Py_INCREF(fPyObject); }
224 virtual ~ItemGetter() { Py_DECREF(fPyObject); }
225 virtual Py_ssize_t size() = 0;
226 virtual PyObject* get() = 0;
227 PyObject* fPyObject;
228};
229
230struct CountedItemGetter : public ItemGetter {
231 CountedItemGetter(PyObject* pyobj) : ItemGetter(pyobj), fCur(0) {}
232 Py_ssize_t fCur;
233};
234
235struct TupleItemGetter : public CountedItemGetter {
236 using CountedItemGetter::CountedItemGetter;
237 Py_ssize_t size() override { return PyTuple_GET_SIZE(fPyObject); }
238 PyObject* get() override {
239 if (fCur < PyTuple_GET_SIZE(fPyObject)) {
240 PyObject* item = PyTuple_GET_ITEM(fPyObject, fCur++);
242 return item;
243 }
244 PyErr_SetString(PyExc_StopIteration, "end of tuple");
245 return nullptr;
246 }
247};
248
249struct ListItemGetter : public CountedItemGetter {
250 using CountedItemGetter::CountedItemGetter;
251 Py_ssize_t size() override { return PyList_GET_SIZE(fPyObject); }
252 PyObject* get() override {
253 if (fCur < PyList_GET_SIZE(fPyObject)) {
254 PyObject* item = PyList_GET_ITEM(fPyObject, fCur++);
256 return item;
257 }
258 PyErr_SetString(PyExc_StopIteration, "end of list");
259 return nullptr;
260 }
261};
262
263struct SequenceItemGetter : public CountedItemGetter {
264 using CountedItemGetter::CountedItemGetter;
265 Py_ssize_t size() override {
266 Py_ssize_t sz = PySequence_Size(fPyObject);
267 if (sz < 0) {
268 PyErr_Clear();
269 return PyObject_LengthHint(fPyObject, 8);
270 }
271 return sz;
272 }
273 PyObject* get() override { return PySequence_GetItem(fPyObject, fCur++); }
274};
275
276struct IterItemGetter : public ItemGetter {
277 using ItemGetter::ItemGetter;
278 Py_ssize_t size() override { return PyObject_LengthHint(fPyObject, 8); }
279 PyObject* get() override { return (*(Py_TYPE(fPyObject)->tp_iternext))(fPyObject); }
280};
281
282static ItemGetter* GetGetter(PyObject* args)
283{
284// Create an ItemGetter to loop over the iterable argument, if any.
285 ItemGetter* getter = nullptr;
286
287 if (PyTuple_GET_SIZE(args) == 1) {
288 PyObject* fi = PyTuple_GET_ITEM(args, 0);
290 return nullptr; // do not accept string to fill std::vector<char>
291
292 // TODO: this only tests for new-style buffers, which is too strict, but a
293 // generic check for Py_TYPE(fi)->tp_as_buffer is too loose (note that the
294 // main use case is numpy, which offers the new interface)
296 return nullptr;
297
299 getter = new TupleItemGetter(fi);
300 else if (PyList_CheckExact(fi))
301 getter = new ListItemGetter(fi);
302 else if (PySequence_Check(fi))
303 getter = new SequenceItemGetter(fi);
304 else {
306 if (iter) {
307 getter = new IterItemGetter{iter};
308 Py_DECREF(iter);
309 }
310 else PyErr_Clear();
311 }
312 }
313
314 return getter;
315}
316
317static bool FillVector(PyObject* vecin, PyObject* args, ItemGetter* getter)
318{
319 Py_ssize_t sz = getter->size();
320 if (sz < 0)
321 return false;
322
323// reserve memory as applicable
324 if (0 < sz) {
325 PyObject* res = PyObject_CallMethod(vecin, (char*)"reserve", (char*)"n", sz);
326 Py_DECREF(res);
327 } else // i.e. sz == 0, so empty container: done
328 return true;
329
330 bool fill_ok = true;
331
332// two main options: a list of lists (or tuples), or a list of objects; the former
333// are emplace_back'ed, the latter push_back'ed
335 if (!fi) PyErr_Clear();
337 // use emplace_back to construct the vector entries one by one
338 PyObject* eb_call = PyObject_GetAttrString(vecin, (char*)"emplace_back");
340 bool value_is_vector = false;
342 // if the value_type is a vector, then allow for initialization from sequences
343 if (std::string(CPyCppyy_PyText_AsString(vtype)).rfind("std::vector", 0) != std::string::npos)
344 value_is_vector = true;
345 } else
346 PyErr_Clear();
348
349 if (eb_call) {
351 for (int i = 0; /* until break */; ++i) {
352 PyObject* item = getter->get();
353 if (item) {
355 eb_args = PyTuple_New(1);
357 } else if (PyTuple_CheckExact(item)) {
358 eb_args = item;
359 } else if (PyList_CheckExact(item)) {
362 for (Py_ssize_t j = 0; j < isz; ++j) {
366 }
368 } else {
370 PyErr_Format(PyExc_TypeError, "argument %d is not a tuple or list", i);
371 fill_ok = false;
372 break;
373 }
376 if (!ebres) {
377 fill_ok = false;
378 break;
379 }
381 } else {
382 if (PyErr_Occurred()) {
385 fill_ok = false;
386 else { PyErr_Clear(); }
387 }
388 break;
389 }
390 }
392 }
393 } else {
394 // use push_back to add the vector entries one by one
395 PyObject* pb_call = PyObject_GetAttrString(vecin, (char*)"push_back");
396 if (pb_call) {
397 for (;;) {
398 PyObject* item = getter->get();
399 if (item) {
402 if (!pbres) {
403 fill_ok = false;
404 break;
405 }
407 } else {
408 if (PyErr_Occurred()) {
411 fill_ok = false;
412 else { PyErr_Clear(); }
413 }
414 break;
415 }
416 }
418 }
419 }
420 Py_XDECREF(fi);
421
422 return fill_ok;
423}
424
425PyObject* VectorIAdd(PyObject* self, PyObject* args, PyObject* /* kwds */)
426{
427// Implement fast __iadd__ on std::vector (generic __iadd__ is in Python)
428 ItemGetter* getter = GetGetter(args);
429
430 if (getter) {
431 bool fill_ok = FillVector(self, args, getter);
432 delete getter;
433
434 if (!fill_ok)
435 return nullptr;
436
438 return self;
439 }
440
441// if no getter, it could still be b/c we have a buffer (e.g. numpy); looping over
442// a buffer here is slow, so use insert() instead
443 if (PyTuple_GET_SIZE(args) == 1) {
444 PyObject* fi = PyTuple_GET_ITEM(args, 0);
447 if (vend) {
448 // when __iadd__ is overriden, the operation does not end with
449 // calling the __iadd__ method, but also assigns the result to the
450 // lhs of the iadd. For example, performing vec += arr, Python
451 // first calls our override, and then does vec = vec.iadd(arr).
454
455 if (!it)
456 return nullptr;
457
458 Py_DECREF(it);
459 // Assign the result of the __iadd__ override to the std::vector
461 return self;
462 }
463 }
464 }
465
466 if (!PyErr_Occurred())
467 PyErr_SetString(PyExc_TypeError, "argument is not iterable");
468 return nullptr; // error already set
469}
470
471
472PyObject* VectorInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
473{
474// Specialized vector constructor to allow construction from containers; allowing
475// such construction from initializer_list instead would possible, but can be
476// error-prone. This use case is common enough for std::vector to implement it
477// directly, except for arrays (which can be passed wholesale) and strings (which
478// won't convert properly as they'll be seen as buffers)
479
480 ItemGetter* getter = GetGetter(args);
481
482 if (getter) {
483 // construct an empty vector, then back-fill it
485 if (!result) {
486 delete getter;
487 return nullptr;
488 }
489
490 bool fill_ok = FillVector(self, args, getter);
491 delete getter;
492
493 if (!fill_ok) {
495 return nullptr;
496 }
497
498 return result;
499 }
500
501// The given argument wasn't iterable: simply forward to regular constructor
503 if (realInit) {
504 PyObject* result = PyObject_Call(realInit, args, nullptr);
506 return result;
507 }
508
509 return nullptr;
510}
511
512//---------------------------------------------------------------------------
514{
515 PyObject* pydata = CallPyObjMethod(self, "__real_data");
517 return pydata;
518
520 if (!pylen) {
521 PyErr_Clear();
522 return pydata;
523 }
524
525 long clen = PyInt_AsLong(pylen);
527
529 ((CPPInstance*)pydata)->CastToArray(clen);
530 return pydata;
531 }
532
533 ((LowLevelView*)pydata)->resize((size_t)clen);
534 return pydata;
535}
536
537
538// This function implements __array__, added to std::vector python proxies and causes
539// a bug (see explanation at Utility::AddToClass(pyclass, "__array__"...) in CPyCppyy::Pythonize)
540// The recursive nature of this function, passes each subarray (pydata) to the next call and only
541// the final buffer is cast to a lowlevel view and resized (in VectorData), resulting in only the
542// first 1D array to be returned. See https://github.com/root-project/root/issues/17729
543// It is temporarily removed to prevent errors due to -Wunused-function, since it is no longer added.
544#if 0
545//---------------------------------------------------------------------------
547{
548 PyObject* pydata = VectorData(self, nullptr);
553 return newarr;
554}
555#endif
556
557//-----------------------------------------------------------------------------
558static PyObject* vector_iter(PyObject* v) {
560 if (!vi) return nullptr;
561
562 vi->ii_container = v;
563
564// tell the iterator code to set a life line if this container is a temporary
565 vi->vi_flags = vectoriterobject::kDefault;
566#if PY_VERSION_HEX >= 0x030e0000
568#else
569 if (Py_REFCNT(v) <= 1 || (((CPPInstance*)v)->fFlags & CPPInstance::kIsValue))
570#endif
572
573 Py_INCREF(v);
574
576 if (pyvalue_type) {
578 if (pyvalue_size) {
579 vi->vi_stride = PyLong_AsLong(pyvalue_size);
581 } else {
582 PyErr_Clear();
583 vi->vi_stride = 0;
584 }
585
587 std::string value_type = CPyCppyy_PyText_AsString(pyvalue_type);
588 value_type = Cppyy::ResolveName(value_type);
589 vi->vi_klass = Cppyy::GetScope(value_type);
590 if (!vi->vi_klass) {
591 // look for a special case of pointer to a class type (which is a builtin, but it
592 // is more useful to treat it polymorphically by allowing auto-downcasts)
593 const std::string& clean_type = TypeManip::clean_type(value_type, false, false);
595 if (c && TypeManip::compound(value_type) == "*") {
596 vi->vi_klass = c;
598 }
599 }
600 if (vi->vi_klass) {
601 vi->vi_converter = nullptr;
602 if (!vi->vi_flags) {
603 if (value_type.back() != '*') // meaning, object stored by-value
605 }
606 } else
607 vi->vi_converter = CPyCppyy::CreateConverter(value_type);
608 if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(value_type);
609
610 } else if (CPPScope_Check(pyvalue_type)) {
611 vi->vi_klass = ((CPPClass*)pyvalue_type)->fCppType;
612 vi->vi_converter = nullptr;
613 if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(vi->vi_klass);
614 if (!vi->vi_flags) vi->vi_flags = vectoriterobject::kNeedLifeLine;
615 }
616
617 PyObject* pydata = CallPyObjMethod(v, "__real_data");
618 if (!pydata || Utility::GetBuffer(pydata, '*', 1, vi->vi_data, false) == 0)
619 vi->vi_data = CPPInstance_Check(pydata) ? ((CPPInstance*)pydata)->GetObjectRaw() : nullptr;
621
622 } else {
623 PyErr_Clear();
624 vi->vi_data = nullptr;
625 vi->vi_stride = 0;
626 vi->vi_converter = nullptr;
627 vi->vi_klass = 0;
628 vi->vi_flags = 0;
629 }
630
632
633 vi->ii_pos = 0;
634 vi->ii_len = PySequence_Size(v);
635
637 return (PyObject*)vi;
638}
639
641{
642// Implement python's __getitem__ for std::vector<>s.
643 if (PySlice_Check(index)) {
644 if (!self->GetObject()) {
645 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
646 return nullptr;
647 }
648
651
652 Py_ssize_t start, stop, step;
654
656 if (!AdjustSlice(nlen, start, stop, step))
657 return nseq;
658
659 const Py_ssize_t sign = step < 0 ? -1 : 1;
660 for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
663 CallPyObjMethod(nseq, "push_back", item);
666 }
667
668 return nseq;
669 }
670
672}
673
674
676
678{
679// std::vector<bool> is a special-case in C++, and its return type depends on
680// the compiler: treat it special here as well
681 if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
683 "require object of type std::vector<bool>, but %s given",
684 Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
685 return nullptr;
686 }
687
688 if (!self->GetObject()) {
689 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
690 return nullptr;
691 }
692
693 if (PySlice_Check(idx)) {
696
697 Py_ssize_t start, stop, step;
700 if (!AdjustSlice(nlen, start, stop, step))
701 return nseq;
702
703 const Py_ssize_t sign = step < 0 ? -1 : 1;
704 for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
707 CallPyObjMethod(nseq, "push_back", item);
710 }
711
712 return nseq;
713 }
714
716 if (!pyindex)
717 return nullptr;
718
721
722// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
723 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
724
725// finally, return the value
726 if (bool((*vb)[index]))
729}
730
732{
733// std::vector<bool> is a special-case in C++, and its return type depends on
734// the compiler: treat it special here as well
735 if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
737 "require object of type std::vector<bool>, but %s given",
738 Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
739 return nullptr;
740 }
741
742 if (!self->GetObject()) {
743 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
744 return nullptr;
745 }
746
747 int bval = 0; PyObject* idx = nullptr;
748 if (!PyArg_ParseTuple(args, const_cast<char*>("Oi:__setitem__"), &idx, &bval))
749 return nullptr;
750
752 if (!pyindex)
753 return nullptr;
754
757
758// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
759 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
760
761// finally, set the value
762 (*vb)[index] = (bool)bval;
763
765}
766
767
768//- array behavior as primitives ----------------------------------------------
769PyObject* ArrayInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
770{
771// std::array is normally only constructed using aggregate initialization, which
772// is a concept that does not exist in python, so use this custom constructor to
773// to fill the array using setitem
774
775 if (args && PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0))) {
776 // construct the empty array, then fill it
778 if (!result)
779 return nullptr;
780
781 PyObject* items = PyTuple_GET_ITEM(args, 0);
783 if (PySequence_Size(self) != fillsz) {
784 PyErr_Format(PyExc_ValueError, "received sequence of size %zd where %zd expected",
787 return nullptr;
788 }
789
791 for (Py_ssize_t i = 0; i < fillsz; ++i) {
797 if (!sires) {
800 return nullptr;
801 } else
803 }
805
806 return result;
807 } else
808 PyErr_Clear();
809
810// The given argument wasn't iterable: simply forward to regular constructor
812 if (realInit) {
813 PyObject* result = PyObject_Call(realInit, args, nullptr);
815 return result;
816 }
817
818 return nullptr;
819}
820
821
822//- map behavior as primitives ------------------------------------------------
824{
825// construct an empty map, then fill it with the key, value pairs
827 if (!result)
828 return nullptr;
829
831 for (Py_ssize_t i = 0; i < PySequence_Size(pairs); ++i) {
833 PyObject* sires = nullptr;
834 if (pair && PySequence_Check(pair) && PySequence_Size(pair) == 2) {
835 PyObject* key = PySequence_GetItem(pair, 0);
839 Py_DECREF(key);
840 }
841 Py_DECREF(pair);
842 if (!sires) {
845 if (!PyErr_Occurred())
846 PyErr_SetString(PyExc_TypeError, "Failed to fill map (argument not a dict or sequence of pairs)");
847 return nullptr;
848 } else
850 }
852
853 return result;
854}
855
856PyObject* MapInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
857{
858// Specialized map constructor to allow construction from mapping containers and
859// from tuples of pairs ("initializer_list style").
860
861// PyMapping_Check is not very discriminatory, as it basically only checks for the
862// existence of __getitem__, hence the most common cases of tuple and list are
863// dropped straight-of-the-bat (the PyMapping_Items call will fail on them).
864 if (PyTuple_GET_SIZE(args) == 1 && PyMapping_Check(PyTuple_GET_ITEM(args, 0)) && \
866 PyObject* assoc = PyTuple_GET_ITEM(args, 0);
867#if PY_VERSION_HEX < 0x03000000
868 // to prevent warning about literal string, expand macro
869 PyObject* items = PyObject_CallMethod(assoc, (char*)"items", nullptr);
870#else
871 // in p3, PyMapping_Items isn't a macro, but a function that short-circuits dict
873#endif
874 if (items && PySequence_Check(items)) {
877 return result;
878 }
879
881 PyErr_Clear();
882
883 // okay to fall through as long as 'self' has not been created (is done in MapFromPairs)
884 }
885
886// tuple of pairs case (some mapping types are sequences)
887 if (PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0)))
888 return MapFromPairs(self, PyTuple_GET_ITEM(args, 0));
889
890// The given argument wasn't a mapping or tuple of pairs: forward to regular constructor
892 if (realInit) {
893 PyObject* result = PyObject_Call(realInit, args, nullptr);
895 return result;
896 }
897
898 return nullptr;
899}
900
901#if __cplusplus <= 202002L
903{
904// Implement python's __contains__ for std::map/std::set
905 PyObject* result = nullptr;
906
907 PyObject* iter = CallPyObjMethod(self, "find", obj);
908 if (CPPInstance_Check(iter)) {
910 if (CPPInstance_Check(end)) {
911 if (!PyObject_RichCompareBool(iter, end, Py_EQ)) {
913 result = Py_True;
914 }
915 }
916 Py_XDECREF(end);
917 }
918 Py_XDECREF(iter);
919
920 if (!result) {
921 PyErr_Clear(); // e.g. wrong argument type, which should always lead to False
924 }
925
926 return result;
927}
928#endif
929
930
931//- set behavior as primitives ------------------------------------------------
932PyObject* SetInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
933{
934// Specialized set constructor to allow construction from Python sets.
935 if (PyTuple_GET_SIZE(args) == 1 && PySet_Check(PyTuple_GET_ITEM(args, 0))) {
936 PyObject* pyset = PyTuple_GET_ITEM(args, 0);
937
938 // construct an empty set, then fill it
940 if (!result)
941 return nullptr;
942
944 if (iter) {
945 PyObject* ins_call = PyObject_GetAttrString(self, (char*)"insert");
946
947 IterItemGetter getter{iter};
948 Py_DECREF(iter);
949
950 PyObject* item = getter.get();
951 while (item) {
954 if (!insres) {
957 return nullptr;
958 } else
960 item = getter.get();
961 }
963 }
964
965 return result;
966 }
967
968// The given argument wasn't iterable: simply forward to regular constructor
970 if (realInit) {
971 PyObject* result = PyObject_Call(realInit, args, nullptr);
973 return result;
974 }
975
976 return nullptr;
977}
978
979
980//- STL container iterator support --------------------------------------------
981static const ptrdiff_t PS_END_ADDR = 7; // non-aligned address, so no clash
982static const ptrdiff_t PS_FLAG_ADDR = 11; // id.
983static const ptrdiff_t PS_COLL_ADDR = 13; // id.
984
986{
987// Implement python's __iter__ for low level views used through STL-type begin()/end()
989
990 if (LowLevelView_Check(iter)) {
991 // builtin pointer iteration: can only succeed if a size is available
993 if (sz == -1) {
994 Py_DECREF(iter);
995 return nullptr;
996 }
997 PyObject* lliter = Py_TYPE(iter)->tp_iter(iter);
998 ((indexiterobject*)lliter)->ii_len = sz;
999 Py_DECREF(iter);
1000 return lliter;
1001 }
1002
1003 if (iter) {
1004 Py_DECREF(iter);
1005 PyErr_SetString(PyExc_TypeError, "unrecognized iterator type for low level views");
1006 }
1007
1008 return nullptr;
1009}
1010
1012{
1013// Implement python's __iter__ for std::iterator<>s
1015 if (iter) {
1017 if (end) {
1018 if (CPPInstance_Check(iter)) {
1019 // use the data member cache to store extra state on the iterator object,
1020 // without it being visible on the Python side
1021 auto& dmc = ((CPPInstance*)iter)->GetDatamemberCache();
1022 dmc.push_back(std::make_pair(PS_END_ADDR, end));
1023
1024 // set a flag, indicating first iteration (reset in __next__)
1026 dmc.push_back(std::make_pair(PS_FLAG_ADDR, Py_False));
1027
1028 // make sure the iterated over collection remains alive for the duration
1029 Py_INCREF(self);
1030 dmc.push_back(std::make_pair(PS_COLL_ADDR, self));
1031 } else {
1032 // could store "end" on the object's dictionary anyway, but if end() returns
1033 // a user-customized object, then its __next__ is probably custom, too
1034 Py_DECREF(end);
1035 }
1036 }
1037 }
1038 return iter;
1039}
1040
1041//- generic iterator support over a sequence with operator[] and size ---------
1042//-----------------------------------------------------------------------------
1043static PyObject* index_iter(PyObject* c) {
1045 if (!ii) return nullptr;
1046
1047 Py_INCREF(c);
1048 ii->ii_container = c;
1049 ii->ii_pos = 0;
1050 ii->ii_len = PySequence_Size(c);
1051
1053 return (PyObject*)ii;
1054}
1055
1056
1057//- safe indexing for STL-like vector w/o iterator dictionaries ---------------
1058/* replaced by indexiterobject iteration, but may still have some future use ...
1059PyObject* CheckedGetItem(PyObject* self, PyObject* obj)
1060{
1061// Implement a generic python __getitem__ for STL-like classes that are missing the
1062// reflection info for their iterators. This is then used for iteration by means of
1063// consecutive indices, it such index is of integer type.
1064 Py_ssize_t size = PySequence_Size(self);
1065 Py_ssize_t idx = PyInt_AsSsize_t(obj);
1066 if ((size == (Py_ssize_t)-1 || idx == (Py_ssize_t)-1) && PyErr_Occurred()) {
1067 // argument conversion problem: let method itself resolve anew and report
1068 PyErr_Clear();
1069 return PyObject_CallMethodOneArg(self, PyStrings::gGetNoCheck, obj);
1070 }
1071
1072 bool inbounds = false;
1073 if (idx < 0) idx += size;
1074 if (0 <= idx && 0 <= size && idx < size)
1075 inbounds = true;
1076
1077 if (inbounds)
1078 return PyObject_CallMethodOneArg(self, PyStrings::gGetNoCheck, obj);
1079 else
1080 PyErr_SetString( PyExc_IndexError, "index out of range" );
1081
1082 return nullptr;
1083}*/
1084
1085
1086//- pair as sequence to allow tuple unpacking --------------------------------
1088{
1089// For std::map<> iteration, unpack std::pair<>s into tuples for the loop.
1090 long idx = PyLong_AsLong(pyindex);
1091 if (idx == -1 && PyErr_Occurred())
1092 return nullptr;
1093
1094 if (!CPPInstance_Check(self) || !((CPPInstance*)self)->GetObject()) {
1095 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
1096 return nullptr;
1097 }
1098
1099 if ((int)idx == 0)
1101 else if ((int)idx == 1)
1103
1104// still here? Trigger stop iteration
1105 PyErr_SetString(PyExc_IndexError, "out of bounds");
1106 return nullptr;
1107}
1108
1109//- simplistic len() functions -----------------------------------------------
1111 return PyInt_FromLong(2);
1112}
1113
1114
1115//- shared/unique_ptr behavior -----------------------------------------------
1116PyObject* SmartPtrInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
1117{
1118// since the shared/unique pointer will take ownership, we need to relinquish it
1120 if (realInit) {
1121 PyObject* result = PyObject_Call(realInit, args, nullptr);
1123 if (result && PyTuple_GET_SIZE(args) == 1 && CPPInstance_Check(PyTuple_GET_ITEM(args, 0))) {
1125 if (!(cppinst->fFlags & CPPInstance::kIsSmartPtr)) cppinst->CppOwns();
1126 }
1127 return result;
1128 }
1129 return nullptr;
1130}
1131
1132
1133//- string behavior as primitives --------------------------------------------
1134#if PY_VERSION_HEX >= 0x03000000
1135// TODO: this is wrong, b/c it doesn't order
1138}
1139#endif
1140static inline
1141PyObject* CPyCppyy_PyString_FromCppString(std::string_view s, bool native=true) {
1142 if (native)
1143 return PyBytes_FromStringAndSize(s.data(), s.size());
1144 return CPyCppyy_PyText_FromStringAndSize(s.data(), s.size());
1145}
1146
1147static inline
1148PyObject* CPyCppyy_PyString_FromCppString(std::wstring_view s, bool native=true) {
1149 PyObject* pyobj = PyUnicode_FromWideChar(s.data(), s.size());
1150 if (pyobj && native) {
1151 PyObject* pybytes = PyUnicode_AsEncodedString(pyobj, "UTF-8", "strict");
1153 pyobj = pybytes;
1154 }
1155 return pyobj;
1156}
1157
1158#define CPPYY_IMPL_STRING_PYTHONIZATION(type, name) \
1159static inline \
1160PyObject* name##StringGetData(PyObject* self, bool native=true) \
1161{ \
1162 if (CPyCppyy::CPPInstance_Check(self)) { \
1163 type* obj = ((type*)((CPPInstance*)self)->GetObject()); \
1164 if (obj) return CPyCppyy_PyString_FromCppString(*obj, native); \
1165 } \
1166 PyErr_Format(PyExc_TypeError, "object mismatch (%s expected)", #type); \
1167 return nullptr; \
1168} \
1169 \
1170PyObject* name##StringStr(PyObject* self) \
1171{ \
1172 PyObject* pyobj = name##StringGetData(self, false); \
1173 if (!pyobj) { \
1174 /* do a native conversion to make printing possible (debatable) */ \
1175 PyErr_Clear(); \
1176 PyObject* pybytes = name##StringGetData(self, true); \
1177 if (pybytes) { /* should not fail */ \
1178 pyobj = PyObject_Str(pybytes); \
1179 Py_DECREF(pybytes); \
1180 } \
1181 } \
1182 return pyobj; \
1183} \
1184 \
1185PyObject* name##StringBytes(PyObject* self) \
1186{ \
1187 return name##StringGetData(self, true); \
1188} \
1189 \
1190PyObject* name##StringRepr(PyObject* self) \
1191{ \
1192 PyObject* data = name##StringGetData(self, true); \
1193 if (data) { \
1194 PyObject* repr = PyObject_Repr(data); \
1195 Py_DECREF(data); \
1196 return repr; \
1197 } \
1198 return nullptr; \
1199} \
1200 \
1201PyObject* name##StringIsEqual(PyObject* self, PyObject* obj) \
1202{ \
1203 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1204 if (data) { \
1205 PyObject* result = PyObject_RichCompare(data, obj, Py_EQ); \
1206 Py_DECREF(data); \
1207 return result; \
1208 } \
1209 return nullptr; \
1210} \
1211 \
1212PyObject* name##StringIsNotEqual(PyObject* self, PyObject* obj) \
1213{ \
1214 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1215 if (data) { \
1216 PyObject* result = PyObject_RichCompare(data, obj, Py_NE); \
1217 Py_DECREF(data); \
1218 return result; \
1219 } \
1220 return nullptr; \
1221}
1222
1223// Only define STLStringCompare:
1224#define CPPYY_IMPL_STRING_PYTHONIZATION_CMP(type, name) \
1225CPPYY_IMPL_STRING_PYTHONIZATION(type, name) \
1226PyObject* name##StringCompare(PyObject* self, PyObject* obj) \
1227{ \
1228 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1229 int result = 0; \
1230 if (data) { \
1231 result = PyObject_Compare(data, obj); \
1232 Py_DECREF(data); \
1233 } \
1234 if (PyErr_Occurred()) \
1235 return nullptr; \
1236 return PyInt_FromLong(result); \
1237}
1238
1242
1243static inline std::string* GetSTLString(CPPInstance* self) {
1244 if (!CPPInstance_Check(self)) {
1245 PyErr_SetString(PyExc_TypeError, "std::string object expected");
1246 return nullptr;
1247 }
1248
1249 std::string* obj = (std::string*)self->GetObject();
1250 if (!obj)
1251 PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
1252
1253 return obj;
1254}
1255
1257{
1258 std::string* obj = GetSTLString(self);
1259 if (!obj)
1260 return nullptr;
1261
1262 char* keywords[] = {(char*)"encoding", (char*)"errors", (char*)nullptr};
1263 const char* encoding = nullptr; const char* errors = nullptr;
1265 const_cast<char*>("s|s"), keywords, &encoding, &errors))
1266 return nullptr;
1267
1268 return PyUnicode_Decode(obj->data(), obj->size(), encoding, errors);
1269}
1270
1271#if __cplusplus <= 202302L
1273{
1274 std::string* obj = GetSTLString(self);
1275 if (!obj)
1276 return nullptr;
1277
1278 const char* needle = CPyCppyy_PyText_AsString(pyobj);
1279 if (!needle)
1280 return nullptr;
1281
1282 if (obj->find(needle) != std::string::npos) {
1284 }
1285
1287}
1288#endif
1289
1291{
1292 std::string* obj = GetSTLString(self);
1293 if (!obj)
1294 return nullptr;
1295
1296// both str and std::string have a method "replace", but the Python version only
1297// accepts strings and takes no keyword arguments, whereas the C++ version has no
1298// overload that takes a string
1299
1300 if (2 <= PyTuple_GET_SIZE(args) && CPyCppyy_PyText_Check(PyTuple_GET_ITEM(args, 0))) {
1301 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());
1302 PyObject* meth = PyObject_GetAttrString(pystr, (char*)"replace");
1305 Py_DECREF(meth);
1306 return result;
1307 }
1308
1309 PyObject* cppreplace = PyObject_GetAttrString((PyObject*)self, (char*)"__cpp_replace");
1310 if (cppreplace) {
1311 PyObject* result = PyObject_Call(cppreplace, args, nullptr);
1313 return result;
1314 }
1315
1316 PyErr_SetString(PyExc_AttributeError, "\'std::string\' object has no attribute \'replace\'");
1317 return nullptr;
1318}
1319
1320#define CPYCPPYY_STRING_FINDMETHOD(name, cppname, pyname) \
1321PyObject* STLString##name(CPPInstance* self, PyObject* args, PyObject* /*kwds*/) \
1322{ \
1323 std::string* obj = GetSTLString(self); \
1324 if (!obj) \
1325 return nullptr; \
1326 \
1327 PyObject* cppmeth = PyObject_GetAttrString((PyObject*)self, (char*)#cppname);\
1328 if (cppmeth) { \
1329 PyObject* result = PyObject_Call(cppmeth, args, nullptr); \
1330 Py_DECREF(cppmeth); \
1331 if (result) { \
1332 if (PyLongOrInt_AsULong64(result) == (PY_ULONG_LONG)std::string::npos) {\
1333 Py_DECREF(result); \
1334 return PyInt_FromLong(-1); \
1335 } \
1336 return result; \
1337 } \
1338 PyErr_Clear(); \
1339 } \
1340 \
1341 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());\
1342 PyObject* pymeth = PyObject_GetAttrString(pystr, (char*)#pyname); \
1343 Py_DECREF(pystr); \
1344 PyObject* result = PyObject_CallObject(pymeth, args); \
1345 Py_DECREF(pymeth); \
1346 return result; \
1347}
1348
1349// both str and std::string have method "find" and "rfin"; try the C++ version first
1350// and fall back on the Python one in case of failure
1353
1355{
1356 std::string* obj = GetSTLString(self);
1357 if (!obj)
1358 return nullptr;
1359
1360 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());
1363 return attr;
1364}
1365
1366
1367#if 0
1369{
1370// force C++ string types conversion to Python str per Python __repr__ requirements
1372 if (!res || CPyCppyy_PyText_Check(res))
1373 return res;
1375 Py_DECREF(res);
1376 return str_res;
1377}
1378
1380{
1381// force C++ string types conversion to Python str per Python __str__ requirements
1383 if (!res || CPyCppyy_PyText_Check(res))
1384 return res;
1386 Py_DECREF(res);
1387 return str_res;
1388}
1389#endif
1390
1392{
1393// std::string objects hash to the same values as Python strings to allow
1394// matches in dictionaries etc.
1397 Py_DECREF(data);
1398 return h;
1399}
1400
1401
1402//- string_view behavior as primitive ----------------------------------------
1404{
1405// if constructed from a Python unicode object, the constructor will convert it
1406// to a temporary byte string, which is likely to go out of scope too soon; so
1407// buffer it as needed
1409 if (realInit) {
1410 PyObject *strbuf = nullptr, *newArgs = nullptr;
1411 if (PyTuple_GET_SIZE(args) == 1) {
1412 PyObject* arg0 = PyTuple_GET_ITEM(args, 0);
1413 if (PyUnicode_Check(arg0)) {
1414 // convert to the expected bytes array to control the temporary
1415 strbuf = PyUnicode_AsEncodedString(arg0, "UTF-8", "strict");
1416 newArgs = PyTuple_New(1);
1419 } else if (PyBytes_Check(arg0)) {
1420 // tie the life time of the provided string to the string_view
1421 Py_INCREF(arg0);
1422 strbuf = arg0;
1423 }
1424 }
1425
1426 PyObject* result = PyObject_Call(realInit, newArgs ? newArgs : args, nullptr);
1427
1430
1431 // if construction was successful and a string buffer was used, add a
1432 // life line to it from the string_view bound object
1433 if (result && self && strbuf)
1436
1437 return result;
1438 }
1439 return nullptr;
1440}
1441
1442
1443//- STL iterator behavior ----------------------------------------------------
1445{
1446// Python iterator protocol __next__ for STL forward iterators.
1447 bool mustIncrement = true;
1448 PyObject* last = nullptr;
1449 if (CPPInstance_Check(self)) {
1450 auto& dmc = ((CPPInstance*)self)->GetDatamemberCache();
1451 for (auto& p: dmc) {
1452 if (p.first == PS_END_ADDR) {
1453 last = p.second;
1454 Py_INCREF(last);
1455 } else if (p.first == PS_FLAG_ADDR) {
1456 mustIncrement = p.second == Py_True;
1457 if (!mustIncrement) {
1458 Py_DECREF(p.second);
1460 p.second = Py_True;
1461 }
1462 }
1463 }
1464 }
1465
1466 PyObject* next = nullptr;
1467 if (last) {
1468 // handle special case of empty container (i.e. self is end)
1469 if (!PyObject_RichCompareBool(last, self, Py_EQ)) {
1470 bool iter_valid = true;
1471 if (mustIncrement) {
1472 // prefer preinc, but allow post-inc; in both cases, it is "self" that has
1473 // the updated state to dereference
1475 if (!iter) {
1476 PyErr_Clear();
1477 static PyObject* dummy = PyInt_FromLong(1l);
1479 }
1481 Py_XDECREF(iter);
1482 }
1483
1484 if (iter_valid) {
1486 if (!next) PyErr_Clear();
1487 }
1488 }
1489 Py_DECREF(last);
1490 }
1491
1492 if (!next) PyErr_SetString(PyExc_StopIteration, "");
1493 return next;
1494}
1495
1496
1497//- STL complex<T> behavior --------------------------------------------------
1498#define COMPLEX_METH_GETSET(name, cppname) \
1499static PyObject* name##ComplexGet(PyObject* self, void*) { \
1500 return PyObject_CallMethodNoArgs(self, cppname); \
1501} \
1502static int name##ComplexSet(PyObject* self, PyObject* value, void*) { \
1503 PyObject* result = PyObject_CallMethodOneArg(self, cppname, value); \
1504 if (result) { \
1505 Py_DECREF(result); \
1506 return 0; \
1507 } \
1508 return -1; \
1509} \
1510PyGetSetDef name##Complex{(char*)#name, (getter)name##ComplexGet, (setter)name##ComplexSet, nullptr, nullptr};
1511
1514
1517 if (!real) return nullptr;
1518 double r = PyFloat_AsDouble(real);
1519 Py_DECREF(real);
1520 if (r == -1. && PyErr_Occurred())
1521 return nullptr;
1522
1524 if (!imag) return nullptr;
1525 double i = PyFloat_AsDouble(imag);
1526 Py_DECREF(imag);
1527 if (i == -1. && PyErr_Occurred())
1528 return nullptr;
1529
1530 return PyComplex_FromDoubles(r, i);
1531}
1532
1535 if (!real) return nullptr;
1536 double r = PyFloat_AsDouble(real);
1537 Py_DECREF(real);
1538 if (r == -1. && PyErr_Occurred())
1539 return nullptr;
1540
1542 if (!imag) return nullptr;
1543 double i = PyFloat_AsDouble(imag);
1544 Py_DECREF(imag);
1545 if (i == -1. && PyErr_Occurred())
1546 return nullptr;
1547
1548 std::ostringstream s;
1549 s << '(' << r << '+' << i << "j)";
1550 return CPyCppyy_PyText_FromString(s.str().c_str());
1551}
1552
1554{
1555 return PyFloat_FromDouble(((std::complex<double>*)self->GetObject())->real());
1556}
1557
1558static int ComplexDRealSet(CPPInstance* self, PyObject* value, void*)
1559{
1560 double d = PyFloat_AsDouble(value);
1561 if (d == -1.0 && PyErr_Occurred())
1562 return -1;
1563 ((std::complex<double>*)self->GetObject())->real(d);
1564 return 0;
1565}
1566
1567PyGetSetDef ComplexDReal{(char*)"real", (getter)ComplexDRealGet, (setter)ComplexDRealSet, nullptr, nullptr};
1568
1569
1571{
1572 return PyFloat_FromDouble(((std::complex<double>*)self->GetObject())->imag());
1573}
1574
1575static int ComplexDImagSet(CPPInstance* self, PyObject* value, void*)
1576{
1577 double d = PyFloat_AsDouble(value);
1578 if (d == -1.0 && PyErr_Occurred())
1579 return -1;
1580 ((std::complex<double>*)self->GetObject())->imag(d);
1581 return 0;
1582}
1583
1584PyGetSetDef ComplexDImag{(char*)"imag", (getter)ComplexDImagGet, (setter)ComplexDImagSet, nullptr, nullptr};
1585
1587{
1588 double r = ((std::complex<double>*)self->GetObject())->real();
1589 double i = ((std::complex<double>*)self->GetObject())->imag();
1590 return PyComplex_FromDoubles(r, i);
1591}
1592
1593
1594} // unnamed namespace
1595
1596
1597//- public functions ---------------------------------------------------------
1598namespace CPyCppyy {
1599 std::set<std::string> gIteratorTypes;
1600}
1601
1602static inline
1603bool run_pythonizors(PyObject* pyclass, PyObject* pyname, const std::vector<PyObject*>& v)
1604{
1605 PyObject* args = PyTuple_New(2);
1608
1609 bool pstatus = true;
1610 for (auto pythonizor : v) {
1612 if (!result) {
1613 pstatus = false; // TODO: detail the error handling
1614 break;
1615 }
1617 }
1618 Py_DECREF(args);
1619
1620 return pstatus;
1621}
1622
1623bool CPyCppyy::Pythonize(PyObject* pyclass, const std::string& name)
1624{
1625// Add pre-defined pythonizations (for STL and ROOT) to classes based on their
1626// signature and/or class name.
1627 if (!pyclass)
1628 return false;
1629
1631
1632//- method name based pythonization ------------------------------------------
1633
1634// for smart pointer style classes that are otherwise not known as such; would
1635// prefer operator-> as that returns a pointer (which is simpler since it never
1636// has to deal with ref-assignment), but operator* plays better with STL iters
1637// and algorithms
1642
1643// for pre-check of nullptr for boolean types
1645#if PY_VERSION_HEX >= 0x03000000
1646 const char* pybool_name = "__bool__";
1647#else
1648 const char* pybool_name = "__nonzero__";
1649#endif
1651 }
1652
1653// for STL containers, and user classes modeled after them
1654// the attribute must be a CPyCppyy overload, otherwise the check gives false
1655// positives in the case where the class has a non-function attribute that is
1656// called "size".
1657 if (HasAttrDirect(pyclass, PyStrings::gSize, /*mustBeCPyCppyy=*/ true)) {
1658 Utility::AddToClass(pyclass, "__len__", "size");
1659 }
1660
1662 Utility::AddToClass(pyclass, "__contains__", "contains");
1663 }
1664
1665 if (!IsTemplatedSTLClass(name, "vector") && // vector is dealt with below
1668 // obtain the name of the return type
1669 const auto& v = Cppyy::GetMethodIndicesFromName(klass->fCppType, "begin");
1670 if (!v.empty()) {
1671 // check return type; if not explicitly an iterator, add it to the "known" return
1672 // types to add the "next" method on use
1674 const std::string& resname = Cppyy::GetMethodResultType(meth);
1675 bool isIterator = gIteratorTypes.find(resname) != gIteratorTypes.end();
1677 if (resname.find("iterator") == std::string::npos)
1678 gIteratorTypes.insert(resname);
1679 isIterator = true;
1680 }
1681
1682 if (isIterator) {
1683 // install iterator protocol a la STL
1686 } else {
1687 // still okay if this is some pointer type of builtin persuasion (general class
1688 // won't work: the return type needs to understand the iterator protocol)
1689 std::string resolved = Cppyy::ResolveName(resname);
1690 if (resolved.back() == '*' && Cppyy::IsBuiltin(resolved.substr(0, resolved.size()-1))) {
1693 }
1694 }
1695 }
1696 }
1697 if (!((PyTypeObject*)pyclass)->tp_iter && // no iterator resolved
1699 // Python will iterate over __getitem__ using integers, but C++ operator[] will never raise
1700 // a StopIteration. A checked getitem (raising IndexError if beyond size()) works in some
1701 // cases but would mess up if operator[] is meant to implement an associative container. So,
1702 // this has to be implemented as an iterator protocol.
1705 }
1706 }
1707
1708// operator==/!= are used in op_richcompare of CPPInstance, which subsequently allows
1709// comparisons to None; if no operator is available, a hook is installed for lazy
1710// lookups in the global and/or class namespace
1711 if (HasAttrDirect(pyclass, PyStrings::gEq, true) && \
1712 Cppyy::GetMethodIndicesFromName(klass->fCppType, "__eq__").empty()) {
1714 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators();
1715 klass->fOperators->fEq = cppol;
1716 // re-insert the forwarding __eq__ from the CPPInstance in case there was a Python-side
1717 // override in the base class
1718 static PyObject* top_eq = nullptr;
1719 if (!top_eq) {
1722 Py_DECREF(top_eq); // make it borrowed
1724 }
1726 }
1727
1728 if (HasAttrDirect(pyclass, PyStrings::gNe, true) && \
1729 Cppyy::GetMethodIndicesFromName(klass->fCppType, "__ne__").empty()) {
1731 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators();
1732 klass->fOperators->fNe = cppol;
1733 // re-insert the forwarding __ne__ (same reason as above for __eq__)
1734 static PyObject* top_ne = nullptr;
1735 if (!top_ne) {
1738 Py_DECREF(top_ne); // make it borrowed
1740 }
1742 }
1743
1744#if 0
1746 // guarantee that the result of __repr__ is a Python string
1747 Utility::AddToClass(pyclass, "__cpp_repr", "__repr__");
1749 }
1750
1752 // guarantee that the result of __str__ is a Python string
1753 Utility::AddToClass(pyclass, "__cpp_str", "__str__");
1755 }
1756#endif
1757
1758 if (Cppyy::IsAggregate(((CPPClass*)pyclass)->fCppType) && name.compare(0, 5, "std::", 5) != 0 &&
1759 name.compare(0, 6, "tuple<", 6) != 0) {
1760 // create a pseudo-constructor to allow initializer-style object creation
1761 Cppyy::TCppType_t kls = ((CPPClass*)pyclass)->fCppType;
1763 if (ndata) {
1764 std::string rname = name;
1766
1767 std::ostringstream initdef;
1768 initdef << "namespace __cppyy_internal {\n"
1769 << "void init_" << rname << "(" << name << "*& self";
1770 bool codegen_ok = true;
1771 std::vector<std::string> arg_types, arg_names, arg_defaults;
1772 arg_types.reserve(ndata); arg_names.reserve(ndata); arg_defaults.reserve(ndata);
1773 for (Cppyy::TCppIndex_t i = 0; i < ndata; ++i) {
1775 continue;
1776
1777 const std::string& txt = Cppyy::GetDatamemberType(kls, i);
1778 const std::string& res = Cppyy::IsEnum(txt) ? txt : Cppyy::ResolveName(txt);
1779 const std::string& cpd = TypeManip::compound(res);
1780 std::string res_clean = TypeManip::clean_type(res, false, true);
1781
1782 if (res_clean == "internal_enum_type_t")
1783 res_clean = txt; // restore (properly scoped name)
1784
1785 if (res.rfind(']') == std::string::npos && res.rfind(')') == std::string::npos) {
1786 if (!cpd.empty()) arg_types.push_back(res_clean+cpd);
1787 else arg_types.push_back("const "+res_clean+"&");
1788 arg_names.push_back(Cppyy::GetDatamemberName(kls, i));
1789 if ((!cpd.empty() && cpd.back() == '*') || Cppyy::IsBuiltin(res_clean))
1790 arg_defaults.push_back("0");
1791 else {
1794 }
1795 } else {
1796 codegen_ok = false; // TODO: how to support arrays, anonymous enums, etc?
1797 break;
1798 }
1799 }
1800
1801 if (codegen_ok && !arg_types.empty()) {
1802 bool defaults_ok = arg_defaults.size() == arg_types.size();
1803 for (std::vector<std::string>::size_type i = 0; i < arg_types.size(); ++i) {
1804 initdef << ", " << arg_types[i] << " " << arg_names[i];
1805 if (defaults_ok) initdef << " = " << arg_defaults[i];
1806 }
1807 initdef << ") {\n self = new " << name << "{";
1808 for (std::vector<std::string>::size_type i = 0; i < arg_names.size(); ++i) {
1809 if (i != 0) initdef << ", ";
1810 initdef << arg_names[i];
1811 }
1812 initdef << "};\n} }";
1813
1814 if (Cppyy::Compile(initdef.str(), true /* silent */)) {
1815 Cppyy::TCppScope_t cis = Cppyy::GetScope("__cppyy_internal");
1816 const auto& mix = Cppyy::GetMethodIndicesFromName(cis, "init_"+rname);
1817 if (mix.size()) {
1818 if (!Utility::AddToClass(pyclass, "__init__",
1819 new CPPFunction(cis, Cppyy::GetMethod(cis, mix[0]))))
1820 PyErr_Clear();
1821 }
1822 }
1823 }
1824 }
1825 }
1826
1827
1828//- class name based pythonization -------------------------------------------
1829
1830 if (IsTemplatedSTLClass(name, "vector")) {
1831
1832 // std::vector<bool> is a special case in C++
1834 if (klass->fCppType == sVectorBoolTypeID) {
1837 } else {
1838 // constructor that takes python collections
1839 Utility::AddToClass(pyclass, "__real_init", "__init__");
1841
1842 // data with size
1843 Utility::AddToClass(pyclass, "__real_data", "data");
1844 PyErr_Clear(); // AddToClass might have failed for data
1846
1847 // The addition of the __array__ utility to std::vector Python proxies causes a
1848 // bug where the resulting array is a single dimension, causing loss of data when
1849 // converting to numpy arrays, for >1dim vectors. Since this C++ pythonization
1850 // was added with the upgrade in 6.32, and is only defined and used recursively,
1851 // the safe option is to disable this function and no longer add it.
1852#if 0
1853 // numpy array conversion
1855#endif
1856
1857 // checked getitem
1859 Utility::AddToClass(pyclass, "_getitem__unchecked", "__getitem__");
1861 }
1862
1863 // vector-optimized iterator protocol
1865
1866 // optimized __iadd__
1868
1869 // helpers for iteration
1870 const std::string& vtype = Cppyy::ResolveName(name+"::value_type");
1871 if (vtype.rfind("value_type") == std::string::npos) { // actually resolved?
1875 }
1876
1877 size_t typesz = Cppyy::SizeOf(name+"::value_type");
1878 if (typesz) {
1882 }
1883 }
1884 }
1885
1886 else if (IsTemplatedSTLClass(name, "array")) {
1887 // constructor that takes python associative collections
1888 Utility::AddToClass(pyclass, "__real_init", "__init__");
1890 }
1891
1892 else if (IsTemplatedSTLClass(name, "map") || IsTemplatedSTLClass(name, "unordered_map")) {
1893 // constructor that takes python associative collections
1894 Utility::AddToClass(pyclass, "__real_init", "__init__");
1896#if __cplusplus <= 202002L
1897 // From C++20, std::map and std::unordered_map already implement a contains() method.
1899#endif
1900 }
1901
1902 else if (IsTemplatedSTLClass(name, "set")) {
1903 // constructor that takes python associative collections
1904 Utility::AddToClass(pyclass, "__real_init", "__init__");
1906
1907#if __cplusplus <= 202002L
1908 // From C++20, std::set already implements a contains() method.
1910#endif
1911 }
1912
1913 else if (IsTemplatedSTLClass(name, "pair")) {
1916 }
1917
1918 if (IsTemplatedSTLClass(name, "shared_ptr") || IsTemplatedSTLClass(name, "unique_ptr")) {
1919 Utility::AddToClass(pyclass, "__real_init", "__init__");
1921 }
1922
1923 else if (!((PyTypeObject*)pyclass)->tp_iter && \
1924 (name.find("iterator") != std::string::npos || gIteratorTypes.find(name) != gIteratorTypes.end())) {
1925 ((PyTypeObject*)pyclass)->tp_iternext = (iternextfunc)STLIterNext;
1929 }
1930
1931 else if (name == "string" || name == "std::string") { // TODO: ask backend as well
1938#if __cplusplus <= 202302L
1939 // From C++23, std::sting already implements a contains() method.
1941#endif
1943 Utility::AddToClass(pyclass, "__cpp_find", "find");
1945 Utility::AddToClass(pyclass, "__cpp_rfind", "rfind");
1947 Utility::AddToClass(pyclass, "__cpp_replace", "replace");
1950
1951 // to allow use of std::string in dictionaries and findable with str
1953 }
1954
1955 else if (name == "basic_string_view<char,char_traits<char> >" || name == "std::basic_string_view<char>") {
1956 Utility::AddToClass(pyclass, "__real_init", "__init__");
1964 }
1965
1966 else if (name == "basic_string<wchar_t,char_traits<wchar_t>,allocator<wchar_t> >" || name == "std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >") {
1973 }
1974
1975 else if (name == "complex<double>" || name == "std::complex<double>") {
1976 Utility::AddToClass(pyclass, "__cpp_real", "real");
1978 Utility::AddToClass(pyclass, "__cpp_imag", "imag");
1982 }
1983
1984 else if (IsTemplatedSTLClass(name, "complex")) {
1985 Utility::AddToClass(pyclass, "__cpp_real", "real");
1987 Utility::AddToClass(pyclass, "__cpp_imag", "imag");
1991 }
1992
1993// direct user access; there are two calls here:
1994// - explicit pythonization: won't fall through to the base classes and is preferred if present
1995// - normal pythonization: only called if explicit isn't present, falls through to base classes
1996 bool bUserOk = true; PyObject* res = nullptr;
2000 bUserOk = (bool)res;
2001 } else {
2003 if (func) {
2004 res = PyObject_CallFunctionObjArgs(func, pyclass, pyname, nullptr);
2005 Py_DECREF(func);
2006 bUserOk = (bool)res;
2007 } else
2008 PyErr_Clear();
2009 }
2010 if (!bUserOk) {
2012 return false;
2013 } else {
2014 Py_XDECREF(res);
2015 // pyname handed to args tuple below
2016 }
2017
2018// call registered pythonizors, if any: first run the namespace-specific pythonizors, then
2019// the global ones (the idea is to allow writing a pythonizor that see all classes)
2020 bool pstatus = true;
2022 auto &pyzMap = pythonizations();
2023 if (!outer_scope.empty()) {
2024 auto p = pyzMap.find(outer_scope);
2025 if (p != pyzMap.end()) {
2027 name.substr(outer_scope.size()+2, std::string::npos).c_str());
2030 }
2031 }
2032
2033 if (pstatus) {
2034 auto p = pyzMap.find("");
2035 if (p != pyzMap.end())
2036 pstatus = run_pythonizors(pyclass, pyname, p->second);
2037 }
2038
2040
2041// phew! all done ...
2042 return pstatus;
2043}
#define Py_TYPE(ob)
Definition CPyCppyy.h:196
#define Py_RETURN_TRUE
Definition CPyCppyy.h:272
#define Py_RETURN_FALSE
Definition CPyCppyy.h:276
#define PyInt_FromSsize_t
Definition CPyCppyy.h:217
#define CPyCppyy_PyText_FromStringAndSize
Definition CPyCppyy.h:85
#define PyBytes_Check
Definition CPyCppyy.h:61
#define PyInt_AsSsize_t
Definition CPyCppyy.h:216
#define CPyCppyy_PySliceCast
Definition CPyCppyy.h:189
#define CPyCppyy_PyText_AsString
Definition CPyCppyy.h:76
long Py_hash_t
Definition CPyCppyy.h:114
static PyObject * PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)
Definition CPyCppyy.h:385
#define PyBytes_FromStringAndSize
Definition CPyCppyy.h:70
#define Py_RETURN_NONE
Definition CPyCppyy.h:268
#define CPyCppyy_PyText_Type
Definition CPyCppyy.h:94
static PyObject * PyObject_CallMethodNoArgs(PyObject *obj, PyObject *name)
Definition CPyCppyy.h:381
#define CPPYY__next__
Definition CPyCppyy.h:112
#define CPyCppyy_PyText_FromString
Definition CPyCppyy.h:81
#define CPyCppyy_PyText_Check
Definition CPyCppyy.h:74
bool PyUnstable_Object_IsUniqueReferencedTemporary(PyObject *pyobject)
_object PyObject
#define CPPYY_IMPL_STRING_PYTHONIZATION_CMP(type, name)
static bool run_pythonizors(PyObject *pyclass, PyObject *pyname, const std::vector< PyObject * > &v)
#define COMPLEX_METH_GETSET(name, cppname)
#define CPYCPPYY_STRING_FINDMETHOD(name, cppname, pyname)
#define PyObject_LengthHint
std::ios_base::fmtflags fFlags
void FillVector(std::vector< double > &v, int size, T *a)
#define d(i)
Definition RSha256.hxx:102
#define c(i)
Definition RSha256.hxx:101
#define h(i)
Definition RSha256.hxx:106
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t attr
char name[80]
Definition TGX11.cxx:110
const_iterator end() const
PyObject * gContains
Definition PyStrings.cxx:10
PyObject * gCTypesType
Definition PyStrings.cxx:40
PyObject * gRealInit
Definition PyStrings.cxx:43
PyObject * gExPythonize
Definition PyStrings.cxx:73
PyObject * gLifeLine
Definition PyStrings.cxx:30
PyObject * gGetItem
Definition PyStrings.cxx:24
PyObject * gCppBool
Definition PyStrings.cxx:12
PyObject * gCppReal
Definition PyStrings.cxx:65
PyObject * gPythonize
Definition PyStrings.cxx:74
PyObject * gTypeCode
Definition PyStrings.cxx:39
PyObject * gPostInc
Definition PyStrings.cxx:19
PyObject * gCppImag
Definition PyStrings.cxx:66
PyObject * gValueSize
Definition PyStrings.cxx:63
PyObject * gSetItem
Definition PyStrings.cxx:26
PyObject * gGetNoCheck
Definition PyStrings.cxx:25
PyObject * gCppRepr
Definition PyStrings.cxx:36
PyObject * gValueType
Definition PyStrings.cxx:62
void cppscope_to_legalname(std::string &cppscope)
std::string clean_type(const std::string &cppname, bool template_strip=true, bool const_strip=true)
std::string compound(const std::string &name)
std::string extract_namespace(const std::string &name)
Py_ssize_t GetBuffer(PyObject *pyobject, char tc, int size, void *&buf, bool check=true)
Definition Utility.cxx:880
bool AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Definition Utility.cxx:186
PyTypeObject VectorIter_Type
static PyObject * GetAttrDirect(PyObject *pyclass, PyObject *pyname)
bool Pythonize(PyObject *pyclass, const std::string &name)
bool CPPOverload_Check(T *object)
Definition CPPOverload.h:94
std::map< std::string, std::vector< PyObject * > > & pythonizations()
bool CPPScope_Check(T *object)
Definition CPPScope.h:81
bool LowLevelView_Check(T *object)
bool CPPInstance_Check(T *object)
PyTypeObject IndexIter_Type
PyObject * gThisModule
Definition CPPMethod.cxx:30
CPYCPPYY_EXTERN Converter * CreateConverter(const std::string &name, cdims_t=0)
std::set< std::string > gIteratorTypes
size_t TCppIndex_t
Definition cpp_cppyy.h:40
RPY_EXPORTED size_t SizeOf(TCppType_t klass)
intptr_t TCppMethod_t
Definition cpp_cppyy.h:38
RPY_EXPORTED bool IsDefaultConstructable(TCppType_t type)
RPY_EXPORTED bool IsEnum(const std::string &type_name)
RPY_EXPORTED std::vector< TCppIndex_t > GetMethodIndicesFromName(TCppScope_t scope, const std::string &name)
RPY_EXPORTED TCppIndex_t GetNumDatamembers(TCppScope_t scope, bool accept_namespace=false)
RPY_EXPORTED bool Compile(const std::string &code, bool silent=false)
RPY_EXPORTED std::string ResolveName(const std::string &cppitem_name)
TCppScope_t TCppType_t
Definition cpp_cppyy.h:35
RPY_EXPORTED bool IsAggregate(TCppType_t type)
RPY_EXPORTED std::string GetScopedFinalName(TCppType_t type)
RPY_EXPORTED bool IsPublicData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED bool IsBuiltin(const std::string &type_name)
RPY_EXPORTED bool IsStaticData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED std::string GetDatamemberType(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED TCppMethod_t GetMethod(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED bool IsSmartPtr(TCppType_t type)
RPY_EXPORTED TCppScope_t GetScope(const std::string &scope_name)
size_t TCppScope_t
Definition cpp_cppyy.h:34
RPY_EXPORTED std::string GetMethodResultType(TCppMethod_t)
RPY_EXPORTED std::string GetDatamemberName(TCppScope_t scope, TCppIndex_t idata)
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)