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-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{
153// Follow operator*() if present (available in python as __deref__), so that
154// smart pointers behave as expected.
156 // TODO: these calls come from TemplateProxy and are unlikely to be needed in practice,
157 // whereas as-is, they can accidentally dereference the result of end() on some STL
158 // containers. Obviously, this is a dumb hack that should be resolved more fundamentally.
160 return nullptr;
161 }
162
164 PyErr_SetString(PyExc_TypeError, "getattr(): attribute name must be string");
165
167 if (!pyptr)
168 return nullptr;
169
170// prevent a potential infinite loop
171 if (Py_TYPE(pyptr) == Py_TYPE(self)) {
174 PyErr_Format(PyExc_AttributeError, "%s has no attribute \'%s\'",
178
180 return nullptr;
181 }
182
185 return result;
186}
187
188//-----------------------------------------------------------------------------
190{
191// Follow operator->() if present (available in python as __follow__), so that
192// smart pointers behave as expected.
194 PyErr_SetString(PyExc_TypeError, "getattr(): attribute name must be string");
195
197 if (!pyptr)
198 return nullptr;
199
202 return result;
203}
204
205//- pointer checking bool converter -------------------------------------------
207{
208 if (!CPPInstance_Check(self)) {
209 PyErr_SetString(PyExc_TypeError, "C++ object proxy expected");
210 return nullptr;
211 }
212
213 if (!((CPPInstance*)self)->GetObject())
215
217}
218
219//- vector behavior as primitives ----------------------------------------------
220#if PY_VERSION_HEX < 0x03040000
221#define PyObject_LengthHint _PyObject_LengthHint
222#endif
223
224// TODO: can probably use the below getters in the InitializerListConverter
225struct ItemGetter {
226 ItemGetter(PyObject* pyobj) : fPyObject(pyobj) { Py_INCREF(fPyObject); }
227 virtual ~ItemGetter() { Py_DECREF(fPyObject); }
228 virtual Py_ssize_t size() = 0;
229 virtual PyObject* get() = 0;
230 PyObject* fPyObject;
231};
232
233struct CountedItemGetter : public ItemGetter {
234 CountedItemGetter(PyObject* pyobj) : ItemGetter(pyobj), fCur(0) {}
235 Py_ssize_t fCur;
236};
237
238struct TupleItemGetter : public CountedItemGetter {
239 using CountedItemGetter::CountedItemGetter;
240 Py_ssize_t size() override { return PyTuple_GET_SIZE(fPyObject); }
241 PyObject* get() override {
242 if (fCur < PyTuple_GET_SIZE(fPyObject)) {
243 PyObject* item = PyTuple_GET_ITEM(fPyObject, fCur++);
245 return item;
246 }
247 PyErr_SetString(PyExc_StopIteration, "end of tuple");
248 return nullptr;
249 }
250};
251
252struct ListItemGetter : public CountedItemGetter {
253 using CountedItemGetter::CountedItemGetter;
254 Py_ssize_t size() override { return PyList_GET_SIZE(fPyObject); }
255 PyObject* get() override {
256 if (fCur < PyList_GET_SIZE(fPyObject)) {
257 PyObject* item = PyList_GET_ITEM(fPyObject, fCur++);
259 return item;
260 }
261 PyErr_SetString(PyExc_StopIteration, "end of list");
262 return nullptr;
263 }
264};
265
266struct SequenceItemGetter : public CountedItemGetter {
267 using CountedItemGetter::CountedItemGetter;
268 Py_ssize_t size() override {
269 Py_ssize_t sz = PySequence_Size(fPyObject);
270 if (sz < 0) {
271 PyErr_Clear();
272 return PyObject_LengthHint(fPyObject, 8);
273 }
274 return sz;
275 }
276 PyObject* get() override { return PySequence_GetItem(fPyObject, fCur++); }
277};
278
279struct IterItemGetter : public ItemGetter {
280 using ItemGetter::ItemGetter;
281 Py_ssize_t size() override { return PyObject_LengthHint(fPyObject, 8); }
282 PyObject* get() override { return (*(Py_TYPE(fPyObject)->tp_iternext))(fPyObject); }
283};
284
285static ItemGetter* GetGetter(PyObject* args)
286{
287// Create an ItemGetter to loop over the iterable argument, if any.
288 ItemGetter* getter = nullptr;
289
290 if (PyTuple_GET_SIZE(args) == 1) {
291 PyObject* fi = PyTuple_GET_ITEM(args, 0);
293 return nullptr; // do not accept string to fill std::vector<char>
294
295 // TODO: this only tests for new-style buffers, which is too strict, but a
296 // generic check for Py_TYPE(fi)->tp_as_buffer is too loose (note that the
297 // main use case is numpy, which offers the new interface)
299 return nullptr;
300
302 getter = new TupleItemGetter(fi);
303 else if (PyList_CheckExact(fi))
304 getter = new ListItemGetter(fi);
305 else if (PySequence_Check(fi))
306 getter = new SequenceItemGetter(fi);
307 else {
309 if (iter) {
310 getter = new IterItemGetter{iter};
311 Py_DECREF(iter);
312 }
313 else PyErr_Clear();
314 }
315 }
316
317 return getter;
318}
319
320namespace {
321
323{
324 static bool compiled = false;
325
326 if (compiled)
327 return;
328
329 compiled = true;
330
331 auto code = R"(
332namespace __cppyy_internal {
333
334template <class T>
335struct ptr_iterator {
336 T *cur;
337 T *end;
338
339 ptr_iterator(T *c, T *e) : cur(c), end(e) {}
340
341 T &operator*() const { return *cur; }
342 ptr_iterator &operator++()
343 {
344 ++cur;
345 return *this;
346 }
347 bool operator==(const ptr_iterator &other) const { return cur == other.cur; }
348 bool operator!=(const ptr_iterator &other) const { return !(*this == other); }
349};
350
351template <class T>
352ptr_iterator<T> make_iter(T *begin, T *end)
353{
354 return {begin, end};
355}
356
357} // namespace __cppyy_internal
358
359// Note: for const span<T>, T is const-qualified here
360template <class T>
361auto __cppyy_internal_begin(T &s) noexcept
362{
363 return __cppyy_internal::make_iter(s.data(), s.data() + s.size());
364}
365
366// Note: for const span<T>, T is const-qualified here
367template <class T>
368auto __cppyy_internal_end(T &s) noexcept
369{
370 // end iterator = begin iterator with cur == end
371 return __cppyy_internal::make_iter(s.data() + s.size(), s.data() + s.size());
372}
373 )";
374 Cppyy::Compile(code, /*silent*/ true);
375}
376
378{
379 static PyObject *pyFunc = nullptr;
380 if (!pyFunc) {
383 pyFunc = PyObject_GetAttrString(py_ns, "__cppyy_internal_begin");
384 if (!pyFunc) {
385 PyErr_Format(PyExc_RuntimeError, "cppyy internal error: failed to locate helper "
386 "'__cppyy_internal_begin' for std::span pythonization");
387 }
388 }
389 return pyFunc;
390}
391
393{
394 static PyObject *pyFunc = nullptr;
395 if (!pyFunc) {
398 pyFunc = PyObject_GetAttrString(py_ns, "__cppyy_internal_end");
399 if (!pyFunc) {
400 PyErr_Format(PyExc_RuntimeError, "cppyy internal error: failed to locate helper "
401 "'__cppyy_internal_end' for std::span pythonization");
402 }
403 }
404 return pyFunc;
405}
406
407} // namespace
408
410{
411 auto begin = spanBegin();
412 if (!begin)
413 return nullptr;
414 return PyObject_CallOneArg(begin, self);
415}
416
418{
419 auto spanEnd();
420 if (!end)
421 return nullptr;
422 return PyObject_CallOneArg(end, self);
423}
424
425static bool FillVector(PyObject* vecin, PyObject* args, ItemGetter* getter)
426{
427 Py_ssize_t sz = getter->size();
428 if (sz < 0)
429 return false;
430
431// reserve memory as applicable
432 if (0 < sz) {
433 PyObject* res = PyObject_CallMethod(vecin, (char*)"reserve", (char*)"n", sz);
434 Py_DECREF(res);
435 } else // i.e. sz == 0, so empty container: done
436 return true;
437
438 bool fill_ok = true;
439
440// two main options: a list of lists (or tuples), or a list of objects; the former
441// are emplace_back'ed, the latter push_back'ed
443 if (!fi) PyErr_Clear();
445 // use emplace_back to construct the vector entries one by one
446 PyObject* eb_call = PyObject_GetAttrString(vecin, (char*)"emplace_back");
448 bool value_is_vector = false;
450 // if the value_type is a vector, then allow for initialization from sequences
451 if (std::string(CPyCppyy_PyText_AsString(vtype)).rfind("std::vector", 0) != std::string::npos)
452 value_is_vector = true;
453 } else
454 PyErr_Clear();
456
457 if (eb_call) {
459 for (int i = 0; /* until break */; ++i) {
460 PyObject* item = getter->get();
461 if (item) {
463 eb_args = PyTuple_New(1);
465 } else if (PyTuple_CheckExact(item)) {
466 eb_args = item;
467 } else if (PyList_CheckExact(item)) {
470 for (Py_ssize_t j = 0; j < isz; ++j) {
474 }
476 } else {
478 PyErr_Format(PyExc_TypeError, "argument %d is not a tuple or list", i);
479 fill_ok = false;
480 break;
481 }
484 if (!ebres) {
485 fill_ok = false;
486 break;
487 }
489 } else {
490 if (PyErr_Occurred()) {
493 fill_ok = false;
494 else { PyErr_Clear(); }
495 }
496 break;
497 }
498 }
500 }
501 } else {
502 // use push_back to add the vector entries one by one
503 PyObject* pb_call = PyObject_GetAttrString(vecin, (char*)"push_back");
504 if (pb_call) {
505 for (;;) {
506 PyObject* item = getter->get();
507 if (item) {
510 if (!pbres) {
511 fill_ok = false;
512 break;
513 }
515 } else {
516 if (PyErr_Occurred()) {
519 fill_ok = false;
520 else { PyErr_Clear(); }
521 }
522 break;
523 }
524 }
526 }
527 }
528 Py_XDECREF(fi);
529
530 return fill_ok;
531}
532
533PyObject* VectorIAdd(PyObject* self, PyObject* args, PyObject* /* kwds */)
534{
535// Implement fast __iadd__ on std::vector (generic __iadd__ is in Python)
536 ItemGetter* getter = GetGetter(args);
537
538 if (getter) {
539 bool fill_ok = FillVector(self, args, getter);
540 delete getter;
541
542 if (!fill_ok)
543 return nullptr;
544
546 return self;
547 }
548
549// if no getter, it could still be b/c we have a buffer (e.g. numpy); looping over
550// a buffer here is slow, so use insert() instead
551 if (PyTuple_GET_SIZE(args) == 1) {
552 PyObject* fi = PyTuple_GET_ITEM(args, 0);
555 if (vend) {
556 // when __iadd__ is overriden, the operation does not end with
557 // calling the __iadd__ method, but also assigns the result to the
558 // lhs of the iadd. For example, performing vec += arr, Python
559 // first calls our override, and then does vec = vec.iadd(arr).
562
563 if (!it)
564 return nullptr;
565
566 Py_DECREF(it);
567 // Assign the result of the __iadd__ override to the std::vector
569 return self;
570 }
571 }
572 }
573
574 if (!PyErr_Occurred())
575 PyErr_SetString(PyExc_TypeError, "argument is not iterable");
576 return nullptr; // error already set
577}
578
579
580PyObject* VectorInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
581{
582// Specialized vector constructor to allow construction from containers; allowing
583// such construction from initializer_list instead would possible, but can be
584// error-prone. This use case is common enough for std::vector to implement it
585// directly, except for arrays (which can be passed wholesale) and strings (which
586// won't convert properly as they'll be seen as buffers)
587
588 ItemGetter* getter = GetGetter(args);
589
590 if (getter) {
591 // construct an empty vector, then back-fill it
593 if (!result) {
594 delete getter;
595 return nullptr;
596 }
597
598 bool fill_ok = FillVector(self, args, getter);
599 delete getter;
600
601 if (!fill_ok) {
603 return nullptr;
604 }
605
606 return result;
607 }
608
609// The given argument wasn't iterable: simply forward to regular constructor
611 if (realInit) {
612 PyObject* result = PyObject_Call(realInit, args, nullptr);
614 return result;
615 }
616
617 return nullptr;
618}
619
620//---------------------------------------------------------------------------
622{
623 PyObject* pydata = CallPyObjMethod(self, "__real_data");
625 return pydata;
626
628 if (!pylen) {
629 PyErr_Clear();
630 return pydata;
631 }
632
633 long clen = PyInt_AsLong(pylen);
635
637 ((CPPInstance*)pydata)->CastToArray(clen);
638 return pydata;
639 }
640
641 ((LowLevelView*)pydata)->resize((size_t)clen);
642 return pydata;
643}
644
645
646// This function implements __array__, added to std::vector python proxies and causes
647// a bug (see explanation at Utility::AddToClass(pyclass, "__array__"...) in CPyCppyy::Pythonize)
648// The recursive nature of this function, passes each subarray (pydata) to the next call and only
649// the final buffer is cast to a lowlevel view and resized (in VectorData), resulting in only the
650// first 1D array to be returned. See https://github.com/root-project/root/issues/17729
651// It is temporarily removed to prevent errors due to -Wunused-function, since it is no longer added.
652#if 0
653//---------------------------------------------------------------------------
655{
656 PyObject* pydata = VectorData(self, nullptr);
661 return newarr;
662}
663#endif
664
665//-----------------------------------------------------------------------------
666static PyObject* vector_iter(PyObject* v) {
668 if (!vi) return nullptr;
669
670 Py_INCREF(v);
671 vi->ii_container = v;
672
673// tell the iterator code to set a life line if this container is a temporary
674 vi->vi_flags = vectoriterobject::kDefault;
675 if (Py_REFCNT(v) <= 2 || (((CPPInstance*)v)->fFlags & CPPInstance::kIsValue))
677
679 if (pyvalue_type) {
681 if (pyvalue_size) {
682 vi->vi_stride = PyLong_AsLong(pyvalue_size);
684 } else {
685 PyErr_Clear();
686 vi->vi_stride = 0;
687 }
688
690 std::string value_type = CPyCppyy_PyText_AsString(pyvalue_type);
691 value_type = Cppyy::ResolveName(value_type);
692 vi->vi_klass = Cppyy::GetScope(value_type);
693 if (!vi->vi_klass) {
694 // look for a special case of pointer to a class type (which is a builtin, but it
695 // is more useful to treat it polymorphically by allowing auto-downcasts)
696 const std::string& clean_type = TypeManip::clean_type(value_type, false, false);
698 if (c && TypeManip::compound(value_type) == "*") {
699 vi->vi_klass = c;
701 }
702 }
703 if (vi->vi_klass) {
704 vi->vi_converter = nullptr;
705 if (!vi->vi_flags) {
706 if (value_type.back() != '*') // meaning, object stored by-value
708 }
709 } else
710 vi->vi_converter = CPyCppyy::CreateConverter(value_type);
711 if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(value_type);
712
713 } else if (CPPScope_Check(pyvalue_type)) {
714 vi->vi_klass = ((CPPClass*)pyvalue_type)->fCppType;
715 vi->vi_converter = nullptr;
716 if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(vi->vi_klass);
717 if (!vi->vi_flags) vi->vi_flags = vectoriterobject::kNeedLifeLine;
718 }
719
720 PyObject* pydata = CallPyObjMethod(v, "__real_data");
721 if (!pydata || Utility::GetBuffer(pydata, '*', 1, vi->vi_data, false) == 0)
722 vi->vi_data = CPPInstance_Check(pydata) ? ((CPPInstance*)pydata)->GetObjectRaw() : nullptr;
724
725 } else {
726 PyErr_Clear();
727 vi->vi_data = nullptr;
728 vi->vi_stride = 0;
729 vi->vi_converter = nullptr;
730 vi->vi_klass = 0;
731 vi->vi_flags = 0;
732 }
733
735
736 vi->ii_pos = 0;
737 vi->ii_len = PySequence_Size(v);
738
740 return (PyObject*)vi;
741}
742
744{
745// Implement python's __getitem__ for std::vector<>s.
746 if (PySlice_Check(index)) {
747 if (!self->GetObject()) {
748 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
749 return nullptr;
750 }
751
754
755 start, stop, step;
757
759 if (!AdjustSlice(nlen, start, stop, step))
760 return nseq;
761
762 const Py_ssize_t sign = step < 0 ? -1 : 1;
763 for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
766 CallPyObjMethod(nseq, "push_back", item);
769 }
770
771 return nseq;
772 }
773
775}
776
777
779
781{
782// std::vector<bool> is a special-case in C++, and its return type depends on
783// the compiler: treat it special here as well
784 if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
786 "require object of type std::vector<bool>, but %s given",
787 Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
788 return nullptr;
789 }
790
791 if (!self->GetObject()) {
792 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
793 return nullptr;
794 }
795
796 if (PySlice_Check(idx)) {
799
800 start, stop, step;
803 if (!AdjustSlice(nlen, start, stop, step))
804 return nseq;
805
806 const Py_ssize_t sign = step < 0 ? -1 : 1;
807 for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
810 CallPyObjMethod(nseq, "push_back", item);
813 }
814
815 return nseq;
816 }
817
819 if (!pyindex)
820 return nullptr;
821
824
825// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
826 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
827
828// finally, return the value
829 if (bool((*vb)[index]))
832}
833
835{
836// std::vector<bool> is a special-case in C++, and its return type depends on
837// the compiler: treat it special here as well
838 if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
840 "require object of type std::vector<bool>, but %s given",
841 Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
842 return nullptr;
843 }
844
845 if (!self->GetObject()) {
846 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
847 return nullptr;
848 }
849
850 int bval = 0; PyObject* idx = nullptr;
851 if (!PyArg_ParseTuple(args, const_cast<char*>("Oi:__setitem__"), &idx, &bval))
852 return nullptr;
853
855 if (!pyindex)
856 return nullptr;
857
860
861// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
862 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
863
864// finally, set the value
865 (*vb)[index] = (bool)bval;
866
868}
869
870
871//- array behavior as primitives ----------------------------------------------
872PyObject* ArrayInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
873{
874// std::array is normally only constructed using aggregate initialization, which
875// is a concept that does not exist in python, so use this custom constructor to
876// to fill the array using setitem
877
878 if (args && PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0))) {
879 // construct the empty array, then fill it
881 if (!result)
882 return nullptr;
883
884 PyObject* items = PyTuple_GET_ITEM(args, 0);
886 if (PySequence_Size(self) != fillsz) {
887 PyErr_Format(PyExc_ValueError, "received sequence of size %zd where %zd expected",
890 return nullptr;
891 }
892
894 for (Py_ssize_t i = 0; i < fillsz; ++i) {
900 if (!sires) {
903 return nullptr;
904 } else
906 }
908
909 return result;
910 } else
911 PyErr_Clear();
912
913// The given argument wasn't iterable: simply forward to regular constructor
915 if (realInit) {
916 PyObject* result = PyObject_Call(realInit, args, nullptr);
918 return result;
919 }
920
921 return nullptr;
922}
923
924
925//- map behavior as primitives ------------------------------------------------
927{
928// construct an empty map, then fill it with the key, value pairs
930 if (!result)
931 return nullptr;
932
934 for (Py_ssize_t i = 0; i < PySequence_Size(pairs); ++i) {
936 PyObject* sires = nullptr;
937 if (pair && PySequence_Check(pair) && PySequence_Size(pair) == 2) {
938 PyObject* key = PySequence_GetItem(pair, 0);
942 Py_DECREF(key);
943 }
944 Py_DECREF(pair);
945 if (!sires) {
948 if (!PyErr_Occurred())
949 PyErr_SetString(PyExc_TypeError, "Failed to fill map (argument not a dict or sequence of pairs)");
950 return nullptr;
951 } else
953 }
955
956 return result;
957}
958
959PyObject* MapInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
960{
961// Specialized map constructor to allow construction from mapping containers and
962// from tuples of pairs ("initializer_list style").
963
964// PyMapping_Check is not very discriminatory, as it basically only checks for the
965// existence of __getitem__, hence the most common cases of tuple and list are
966// dropped straight-of-the-bat (the PyMapping_Items call will fail on them).
967 if (PyTuple_GET_SIZE(args) == 1 && PyMapping_Check(PyTuple_GET_ITEM(args, 0)) && \
969 PyObject* assoc = PyTuple_GET_ITEM(args, 0);
970#if PY_VERSION_HEX < 0x03000000
971 // to prevent warning about literal string, expand macro
972 PyObject* items = PyObject_CallMethod(assoc, (char*)"items", nullptr);
973#else
974 // in p3, PyMapping_Items isn't a macro, but a function that short-circuits dict
976#endif
977 if (items && PySequence_Check(items)) {
980 return result;
981 }
982
984 PyErr_Clear();
985
986 // okay to fall through as long as 'self' has not been created (is done in MapFromPairs)
987 }
988
989// tuple of pairs case (some mapping types are sequences)
990 if (PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0)))
991 return MapFromPairs(self, PyTuple_GET_ITEM(args, 0));
992
993// The given argument wasn't a mapping or tuple of pairs: forward to regular constructor
995 if (realInit) {
996 PyObject* result = PyObject_Call(realInit, args, nullptr);
998 return result;
999 }
1000
1001 return nullptr;
1002}
1003
1005{
1006// Implement python's __contains__ for std::map/std::set
1007 PyObject* result = nullptr;
1008
1009 PyObject* iter = CallPyObjMethod(self, "find", obj);
1010 if (CPPInstance_Check(iter)) {
1011 PyStrings::gEnd);
1012 if (CPPInstance_Check(end)) {
1013 if (!PyObject_RichCompareBool(iter, end, Py_EQ)) {
1015 result = Py_True;
1016 }
1017 }
1018 Py_XDECREF(end);
1019 }
1020 Py_XDECREF(iter);
1021
1022 if (!result) {
1023 PyErr_Clear(); // e.g. wrong argument type, which should always lead to False
1025 result = Py_False;
1026 }
1027
1028 return result;
1029}
1030
1031
1032//- set behavior as primitives ------------------------------------------------
1033PyObject* SetInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
1034{
1035// Specialized set constructor to allow construction from Python sets.
1036 if (PyTuple_GET_SIZE(args) == 1 && PySet_Check(PyTuple_GET_ITEM(args, 0))) {
1037 PyObject* pyset = PyTuple_GET_ITEM(args, 0);
1038
1039 // construct an empty set, then fill it
1041 if (!result)
1042 return nullptr;
1043
1045 if (iter) {
1046 PyObject* ins_call = PyObject_GetAttrString(self, (char*)"insert");
1047
1048 IterItemGetter getter{iter};
1049 Py_DECREF(iter);
1050
1051 PyObject* item = getter.get();
1052 while (item) {
1054 Py_DECREF(item);
1055 if (!insres) {
1058 return nullptr;
1059 } else
1061 item = getter.get();
1062 }
1064 }
1065
1066 return result;
1067 }
1068
1069// The given argument wasn't iterable: simply forward to regular constructor
1071 if (realInit) {
1072 PyObject* result = PyObject_Call(realInit, args, nullptr);
1074 return result;
1075 }
1076
1077 return nullptr;
1078}
1079
1080
1081//- STL container iterator support --------------------------------------------
1082static const ptrdiff_t PS_END_ADDR = 7; // non-aligned address, so no clash
1083static const ptrdiff_t PS_FLAG_ADDR = 11; // id.
1084static const ptrdiff_t PS_COLL_ADDR = 13; // id.
1085
1087{
1088// Implement python's __iter__ for low level views used through STL-type begin()/end()
1090
1091 if (LowLevelView_Check(iter)) {
1092 // builtin pointer iteration: can only succeed if a size is available
1094 if (sz == -1) {
1095 Py_DECREF(iter);
1096 return nullptr;
1097 }
1098 PyObject* lliter = Py_TYPE(iter)->tp_iter(iter);
1099 ((indexiterobject*)lliter)->ii_len = sz;
1100 Py_DECREF(iter);
1101 return lliter;
1102 }
1103
1104 if (iter) {
1105 Py_DECREF(iter);
1106 PyErr_SetString(PyExc_TypeError, "unrecognized iterator type for low level views");
1107 }
1108
1109 return nullptr;
1110}
1111
1113{
1114// Implement python's __iter__ for std::iterator<>s
1116 if (iter) {
1117 PyStrings::gEnd);
1118 if (end) {
1119 if (CPPInstance_Check(iter)) {
1120 // use the data member cache to store extra state on the iterator object,
1121 // without it being visible on the Python side
1122 auto& dmc = ((CPPInstance*)iter)->GetDatamemberCache();
1123 dmc.push_back(std::make_pair(PS_END_ADDR, end));
1124
1125 // set a flag, indicating first iteration (reset in __next__)
1127 dmc.push_back(std::make_pair(PS_FLAG_ADDR, Py_False));
1128
1129 // make sure the iterated over collection remains alive for the duration
1130 Py_INCREF(self);
1131 dmc.push_back(std::make_pair(PS_COLL_ADDR, self));
1132 } else {
1133 // could store "end" on the object's dictionary anyway, but if end() returns
1134 // a user-customized object, then its __next__ is probably custom, too
1135 Py_DECREF(end);
1136 }
1137 }
1138 }
1139 return iter;
1140}
1141
1142//- generic iterator support over a sequence with operator[] and size ---------
1143//-----------------------------------------------------------------------------
1144static PyObject* index_iter(PyObject* c) {
1146 if (!ii) return nullptr;
1147
1148 Py_INCREF(c);
1149 ii->ii_container = c;
1150 ii->ii_pos = 0;
1151 ii->ii_len = PySequence_Size(c);
1152
1154 return (PyObject*)ii;
1155}
1156
1157
1158//- safe indexing for STL-like vector w/o iterator dictionaries ---------------
1159/* replaced by indexiterobject iteration, but may still have some future use ...
1160PyObject* CheckedGetItem(PyObject* self, PyObject* obj)
1161{
1162// Implement a generic python __getitem__ for STL-like classes that are missing the
1163// reflection info for their iterators. This is then used for iteration by means of
1164// consecutive indices, it such index is of integer type.
1165 Py_ssize_t size = PySequence_Size(self);
1166 Py_ssize_t idx = PyInt_AsSsize_t(obj);
1167 if ((size == (Py_ssize_t)-1 || idx == (Py_ssize_t)-1) && PyErr_Occurred()) {
1168 // argument conversion problem: let method itself resolve anew and report
1169 PyErr_Clear();
1170 return PyObject_CallMethodOneArg(self, PyStrings::gGetNoCheck, obj);
1171 }
1172
1173 bool inbounds = false;
1174 if (idx < 0) idx += size;
1175 if (0 <= idx && 0 <= size && idx < size)
1176 inbounds = true;
1177
1178 if (inbounds)
1179 return PyObject_CallMethodOneArg(self, PyStrings::gGetNoCheck, obj);
1180 else
1181 PyErr_SetString( PyExc_IndexError, "index out of range" );
1182
1183 return nullptr;
1184}*/
1185
1186
1187//- pair as sequence to allow tuple unpacking --------------------------------
1189{
1190// For std::map<> iteration, unpack std::pair<>s into tuples for the loop.
1191 long idx = PyLong_AsLong(pyindex);
1192 if (idx == -1 && PyErr_Occurred())
1193 return nullptr;
1194
1195 if (!CPPInstance_Check(self) || !((CPPInstance*)self)->GetObject()) {
1196 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
1197 return nullptr;
1198 }
1199
1200 if ((int)idx == 0)
1202 else if ((int)idx == 1)
1204
1205// still here? Trigger stop iteration
1206 PyErr_SetString(PyExc_IndexError, "out of bounds");
1207 return nullptr;
1208}
1209
1210//- simplistic len() functions -----------------------------------------------
1212 return PyInt_FromLong(2);
1213}
1214
1215
1216//- shared/unique_ptr behavior -----------------------------------------------
1217PyObject* SmartPtrInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
1218{
1219// since the shared/unique pointer will take ownership, we need to relinquish it
1221 if (realInit) {
1222 PyObject* result = PyObject_Call(realInit, args, nullptr);
1224 if (result && PyTuple_GET_SIZE(args) == 1 && CPPInstance_Check(PyTuple_GET_ITEM(args, 0))) {
1226 if (!(cppinst->fFlags & CPPInstance::kIsSmartPtr)) cppinst->CppOwns();
1227 }
1228 return result;
1229 }
1230 return nullptr;
1231}
1232
1233
1234//- string behavior as primitives --------------------------------------------
1235#if PY_VERSION_HEX >= 0x03000000
1236// TODO: this is wrong, b/c it doesn't order
1239}
1240#endif
1241static inline
1242PyObject* CPyCppyy_PyString_FromCppString(std::string_view s, bool native=true) {
1243 if (native)
1244 return PyBytes_FromStringAndSize(s.data(), s.size());
1245 return CPyCppyy_PyText_FromStringAndSize(s.data(), s.size());
1246}
1247
1248static inline
1249PyObject* CPyCppyy_PyString_FromCppString(std::wstring_view s, bool native=true) {
1250 PyObject* pyobj = PyUnicode_FromWideChar(s.data(), s.size());
1251 if (pyobj && native) {
1252 PyObject* pybytes = PyUnicode_AsEncodedString(pyobj, "UTF-8", "strict");
1254 pyobj = pybytes;
1255 }
1256 return pyobj;
1257}
1258
1259#define CPPYY_IMPL_STRING_PYTHONIZATION(type, name) \
1260static inline \
1261PyObject* name##StringGetData(PyObject* self, bool native=true) \
1262{ \
1263 if (CPyCppyy::CPPInstance_Check(self)) { \
1264 type* obj = ((type*)((CPPInstance*)self)->GetObject()); \
1265 if (obj) return CPyCppyy_PyString_FromCppString(*obj, native); \
1266 } \
1267 PyErr_Format(PyExc_TypeError, "object mismatch (%s expected)", #type); \
1268 return nullptr; \
1269} \
1270 \
1271PyObject* name##StringStr(PyObject* self) \
1272{ \
1273 PyObject* pyobj = name##StringGetData(self, false); \
1274 if (!pyobj) { \
1275 /* do a native conversion to make printing possible (debatable) */ \
1276 PyErr_Clear(); \
1277 PyObject* pybytes = name##StringGetData(self, true); \
1278 if (pybytes) { /* should not fail */ \
1279 pyobj = PyObject_Str(pybytes); \
1280 Py_DECREF(pybytes); \
1281 } \
1282 } \
1283 return pyobj; \
1284} \
1285 \
1286PyObject* name##StringBytes(PyObject* self) \
1287{ \
1288 return name##StringGetData(self, true); \
1289} \
1290 \
1291PyObject* name##StringRepr(PyObject* self) \
1292{ \
1293 PyObject* data = name##StringGetData(self, true); \
1294 if (data) { \
1295 PyObject* repr = PyObject_Repr(data); \
1296 Py_DECREF(data); \
1297 return repr; \
1298 } \
1299 return nullptr; \
1300} \
1301 \
1302PyObject* name##StringIsEqual(PyObject* self, PyObject* obj) \
1303{ \
1304 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1305 if (data) { \
1306 PyObject* result = PyObject_RichCompare(data, obj, Py_EQ); \
1307 Py_DECREF(data); \
1308 return result; \
1309 } \
1310 return nullptr; \
1311} \
1312 \
1313PyObject* name##StringIsNotEqual(PyObject* self, PyObject* obj) \
1314{ \
1315 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1316 if (data) { \
1317 PyObject* result = PyObject_RichCompare(data, obj, Py_NE); \
1318 Py_DECREF(data); \
1319 return result; \
1320 } \
1321 return nullptr; \
1322}
1323
1324// Only define STLStringCompare:
1325#define CPPYY_IMPL_STRING_PYTHONIZATION_CMP(type, name) \
1326CPPYY_IMPL_STRING_PYTHONIZATION(type, name) \
1327PyObject* name##StringCompare(PyObject* self, PyObject* obj) \
1328{ \
1329 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1330 int result = 0; \
1331 if (data) { \
1332 result = PyObject_Compare(data, obj); \
1333 Py_DECREF(data); \
1334 } \
1335 if (PyErr_Occurred()) \
1336 return nullptr; \
1337 return PyInt_FromLong(result); \
1338}
1339
1343
1344static inline std::string* GetSTLString(CPPInstance* self) {
1345 if (!CPPInstance_Check(self)) {
1346 PyErr_SetString(PyExc_TypeError, "std::string object expected");
1347 return nullptr;
1348 }
1349
1350 std::string* obj = (std::string*)self->GetObject();
1351 if (!obj)
1352 PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
1353
1354 return obj;
1355}
1356
1358{
1359 std::string* obj = GetSTLString(self);
1360 if (!obj)
1361 return nullptr;
1362
1363 char* keywords[] = {(char*)"encoding", (char*)"errors", (char*)nullptr};
1364 const char* encoding = nullptr; const char* errors = nullptr;
1366 const_cast<char*>("s|s"), keywords, &encoding, &errors))
1367 return nullptr;
1368
1369 return PyUnicode_Decode(obj->data(), obj->size(), encoding, errors);
1370}
1371
1373{
1374 std::string* obj = GetSTLString(self);
1375 if (!obj)
1376 return nullptr;
1377
1378 const char* needle = CPyCppyy_PyText_AsString(pyobj);
1379 if (!needle)
1380 return nullptr;
1381
1382 if (obj->find(needle) != std::string::npos) {
1384 }
1385
1387}
1388
1390{
1391 std::string* obj = GetSTLString(self);
1392 if (!obj)
1393 return nullptr;
1394
1395// both str and std::string have a method "replace", but the Python version only
1396// accepts strings and takes no keyword arguments, whereas the C++ version has no
1397// overload that takes a string
1398
1399 if (2 <= PyTuple_GET_SIZE(args) && CPyCppyy_PyText_Check(PyTuple_GET_ITEM(args, 0))) {
1400 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());
1401 PyObject* meth = PyObject_GetAttrString(pystr, (char*)"replace");
1404 Py_DECREF(meth);
1405 return result;
1406 }
1407
1408 PyObject* cppreplace = PyObject_GetAttrString((PyObject*)self, (char*)"__cpp_replace");
1409 if (cppreplace) {
1410 PyObject* result = PyObject_Call(cppreplace, args, nullptr);
1412 return result;
1413 }
1414
1415 PyErr_SetString(PyExc_AttributeError, "\'std::string\' object has no attribute \'replace\'");
1416 return nullptr;
1417}
1418
1419#define CPYCPPYY_STRING_FINDMETHOD(name, cppname, pyname) \
1420PyObject* STLString##name(CPPInstance* self, PyObject* args, PyObject* /*kwds*/) \
1421{ \
1422 std::string* obj = GetSTLString(self); \
1423 if (!obj) \
1424 return nullptr; \
1425 \
1426 PyObject* cppmeth = PyObject_GetAttrString((PyObject*)self, (char*)#cppname);\
1427 if (cppmeth) { \
1428 PyObject* result = PyObject_Call(cppmeth, args, nullptr); \
1429 Py_DECREF(cppmeth); \
1430 if (result) { \
1431 if (PyLongOrInt_AsULong64(result) == (PY_ULONG_LONG)std::string::npos) {\
1432 Py_DECREF(result); \
1433 return PyInt_FromLong(-1); \
1434 } \
1435 return result; \
1436 } \
1437 PyErr_Clear(); \
1438 } \
1439 \
1440 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());\
1441 PyObject* pymeth = PyObject_GetAttrString(pystr, (char*)#pyname); \
1442 Py_DECREF(pystr); \
1443 PyObject* result = PyObject_CallObject(pymeth, args); \
1444 Py_DECREF(pymeth); \
1445 return result; \
1446}
1447
1448// both str and std::string have method "find" and "rfin"; try the C++ version first
1449// and fall back on the Python one in case of failure
1452
1454{
1455 std::string* obj = GetSTLString(self);
1456 if (!obj)
1457 return nullptr;
1458
1459 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());
1462 return attr;
1463}
1464
1465
1466#if 0
1468{
1469// force C++ string types conversion to Python str per Python __repr__ requirements
1471 if (!res || CPyCppyy_PyText_Check(res))
1472 return res;
1474 Py_DECREF(res);
1475 return str_res;
1476}
1477
1479{
1480// force C++ string types conversion to Python str per Python __str__ requirements
1482 if (!res || CPyCppyy_PyText_Check(res))
1483 return res;
1485 Py_DECREF(res);
1486 return str_res;
1487}
1488#endif
1489
1491{
1492// std::string objects hash to the same values as Python strings to allow
1493// matches in dictionaries etc.
1496 Py_DECREF(data);
1497 return h;
1498}
1499
1500
1501//- string_view behavior as primitive ----------------------------------------
1503{
1504// if constructed from a Python unicode object, the constructor will convert it
1505// to a temporary byte string, which is likely to go out of scope too soon; so
1506// buffer it as needed
1508 if (realInit) {
1509 PyObject *strbuf = nullptr, *newArgs = nullptr;
1510 if (PyTuple_GET_SIZE(args) == 1) {
1511 PyObject* arg0 = PyTuple_GET_ITEM(args, 0);
1512 if (PyUnicode_Check(arg0)) {
1513 // convert to the expected bytes array to control the temporary
1514 strbuf = PyUnicode_AsEncodedString(arg0, "UTF-8", "strict");
1515 newArgs = PyTuple_New(1);
1518 } else if (PyBytes_Check(arg0)) {
1519 // tie the life time of the provided string to the string_view
1520 Py_INCREF(arg0);
1521 strbuf = arg0;
1522 }
1523 }
1524
1525 PyObject* result = PyObject_Call(realInit, newArgs ? newArgs : args, nullptr);
1526
1529
1530 // if construction was successful and a string buffer was used, add a
1531 // life line to it from the string_view bound object
1532 if (result && self && strbuf)
1535
1536 return result;
1537 }
1538 return nullptr;
1539}
1540
1541
1542//- STL iterator behavior ----------------------------------------------------
1544{
1545// Python iterator protocol __next__ for STL forward iterators.
1546 bool mustIncrement = true;
1547 PyObject* last = nullptr;
1548 if (CPPInstance_Check(self)) {
1549 auto& dmc = ((CPPInstance*)self)->GetDatamemberCache();
1550 for (auto& p: dmc) {
1551 if (p.first == PS_END_ADDR) {
1552 last = p.second;
1553 Py_INCREF(last);
1554 } else if (p.first == PS_FLAG_ADDR) {
1555 mustIncrement = p.second == Py_True;
1556 if (!mustIncrement) {
1557 Py_DECREF(p.second);
1559 p.second = Py_True;
1560 }
1561 }
1562 }
1563 }
1564
1565 PyObject* next = nullptr;
1566 if (last) {
1567 // handle special case of empty container (i.e. self is end)
1568 if (!PyObject_RichCompareBool(last, self, Py_EQ)) {
1569 bool iter_valid = true;
1570 if (mustIncrement) {
1571 // prefer preinc, but allow post-inc; in both cases, it is "self" that has
1572 // the updated state to dereference
1574 if (!iter) {
1575 PyErr_Clear();
1576 static PyObject* dummy = PyInt_FromLong(1l);
1578 }
1580 Py_XDECREF(iter);
1581 }
1582
1583 if (iter_valid) {
1585 if (!next) PyErr_Clear();
1586 }
1587 }
1588 Py_DECREF(last);
1589 }
1590
1591 if (!next) PyErr_SetString(PyExc_StopIteration, "");
1592 return next;
1593}
1594
1595
1596//- STL complex<T> behavior --------------------------------------------------
1597#define COMPLEX_METH_GETSET(name, cppname) \
1598static PyObject* name##ComplexGet(PyObject* self, void*) { \
1599 return PyObject_CallMethodNoArgs(self, cppname); \
1600} \
1601static int name##ComplexSet(PyObject* self, PyObject* value, void*) { \
1602 PyObject* result = PyObject_CallMethodOneArg(self, cppname, value); \
1603 if (result) { \
1604 Py_DECREF(result); \
1605 return 0; \
1606 } \
1607 return -1; \
1608} \
1609PyGetSetDef name##Complex{(char*)#name, (getter)name##ComplexGet, (setter)name##ComplexSet, nullptr, nullptr};
1610
1613
1616 if (!real) return nullptr;
1617 double r = PyFloat_AsDouble(real);
1618 Py_DECREF(real);
1619 if (r == -1. && PyErr_Occurred())
1620 return nullptr;
1621
1623 if (!imag) return nullptr;
1624 double i = PyFloat_AsDouble(imag);
1625 Py_DECREF(imag);
1626 if (i == -1. && PyErr_Occurred())
1627 return nullptr;
1628
1629 return PyComplex_FromDoubles(r, i);
1630}
1631
1634 if (!real) return nullptr;
1635 double r = PyFloat_AsDouble(real);
1636 Py_DECREF(real);
1637 if (r == -1. && PyErr_Occurred())
1638 return nullptr;
1639
1641 if (!imag) return nullptr;
1642 double i = PyFloat_AsDouble(imag);
1643 Py_DECREF(imag);
1644 if (i == -1. && PyErr_Occurred())
1645 return nullptr;
1646
1647 std::ostringstream s;
1648 s << '(' << r << '+' << i << "j)";
1649 return CPyCppyy_PyText_FromString(s.str().c_str());
1650}
1651
1653{
1654 return PyFloat_FromDouble(((std::complex<double>*)self->GetObject())->real());
1655}
1656
1657static int ComplexDRealSet(CPPInstance* self, PyObject* value, void*)
1658{
1659 double d = PyFloat_AsDouble(value);
1660 if (d == -1.0 && PyErr_Occurred())
1661 return -1;
1662 ((std::complex<double>*)self->GetObject())->real(d);
1663 return 0;
1664}
1665
1666PyGetSetDef ComplexDReal{(char*)"real", (getter)ComplexDRealGet, (setter)ComplexDRealSet, nullptr, nullptr};
1667
1668
1670{
1671 return PyFloat_FromDouble(((std::complex<double>*)self->GetObject())->imag());
1672}
1673
1674static int ComplexDImagSet(CPPInstance* self, PyObject* value, void*)
1675{
1676 double d = PyFloat_AsDouble(value);
1677 if (d == -1.0 && PyErr_Occurred())
1678 return -1;
1679 ((std::complex<double>*)self->GetObject())->imag(d);
1680 return 0;
1681}
1682
1683PyGetSetDef ComplexDImag{(char*)"imag", (getter)ComplexDImagGet, (setter)ComplexDImagSet, nullptr, nullptr};
1684
1686{
1687 double r = ((std::complex<double>*)self->GetObject())->real();
1688 double i = ((std::complex<double>*)self->GetObject())->imag();
1689 return PyComplex_FromDoubles(r, i);
1690}
1691
1692
1693} // unnamed namespace
1694
1695
1696//- public functions ---------------------------------------------------------
1697namespace CPyCppyy {
1698 std::set<std::string> gIteratorTypes;
1699}
1700
1701static inline
1702bool run_pythonizors(PyObject* pyclass, PyObject* pyname, const std::vector<PyObject*>& v)
1703{
1704 PyObject* args = PyTuple_New(2);
1707
1708 bool pstatus = true;
1709 for (auto pythonizor : v) {
1711 if (!result) {
1712 pstatus = false; // TODO: detail the error handling
1713 break;
1714 }
1716 }
1717 Py_DECREF(args);
1718
1719 return pstatus;
1720}
1721
1722bool CPyCppyy::Pythonize(PyObject* pyclass, const std::string& name)
1723{
1724// Add pre-defined pythonizations (for STL and ROOT) to classes based on their
1725// signature and/or class name.
1726 if (!pyclass)
1727 return false;
1728
1730
1731//- method name based pythonization ------------------------------------------
1732
1733// for smart pointer style classes that are otherwise not known as such; would
1734// prefer operator-> as that returns a pointer (which is simpler since it never
1735// has to deal with ref-assignment), but operator* plays better with STL iters
1736// and algorithms
1741
1742// for pre-check of nullptr for boolean types
1744#if PY_VERSION_HEX >= 0x03000000
1745 const char* pybool_name = "__bool__";
1746#else
1747 const char* pybool_name = "__nonzero__";
1748#endif
1750 }
1751
1752// for STL containers, and user classes modeled after them
1753// the attribute must be a CPyCppyy overload, otherwise the check gives false
1754// positives in the case where the class has a non-function attribute that is
1755// called "size".
1756 if (HasAttrDirect(pyclass, PyStrings::gSize, /*mustBeCPyCppyy=*/ true)) {
1757 Utility::AddToClass(pyclass, "__len__", "size");
1758 }
1759
1760 if (!IsTemplatedSTLClass(name, "vector") && // vector is dealt with below
1763 // obtain the name of the return type
1764 const auto& v = Cppyy::GetMethodIndicesFromName(klass->fCppType, "begin");
1765 if (!v.empty()) {
1766 // check return type; if not explicitly an iterator, add it to the "known" return
1767 // types to add the "next" method on use
1769 const std::string& resname = Cppyy::GetMethodResultType(meth);
1770 bool isIterator = gIteratorTypes.find(resname) != gIteratorTypes.end();
1772 if (resname.find("iterator") == std::string::npos)
1773 gIteratorTypes.insert(resname);
1774 isIterator = true;
1775 }
1776
1777 if (isIterator) {
1778 // install iterator protocol a la STL
1781 } else {
1782 // still okay if this is some pointer type of builtin persuasion (general class
1783 // won't work: the return type needs to understand the iterator protocol)
1784 std::string resolved = Cppyy::ResolveName(resname);
1785 if (resolved.back() == '*' && Cppyy::IsBuiltin(resolved.substr(0, resolved.size()-1))) {
1788 }
1789 }
1790 }
1791 }
1792 if (!((PyTypeObject*)pyclass)->tp_iter && // no iterator resolved
1794 // Python will iterate over __getitem__ using integers, but C++ operator[] will never raise
1795 // a StopIteration. A checked getitem (raising IndexError if beyond size()) works in some
1796 // cases but would mess up if operator[] is meant to implement an associative container. So,
1797 // this has to be implemented as an iterator protocol.
1800 }
1801 }
1802
1803// operator==/!= are used in op_richcompare of CPPInstance, which subsequently allows
1804// comparisons to None; if no operator is available, a hook is installed for lazy
1805// lookups in the global and/or class namespace
1806 if (HasAttrDirect(pyclass, PyStrings::gEq, true) && \
1807 Cppyy::GetMethodIndicesFromName(klass->fCppType, "__eq__").empty()) {
1809 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators();
1810 klass->fOperators->fEq = cppol;
1811 // re-insert the forwarding __eq__ from the CPPInstance in case there was a Python-side
1812 // override in the base class
1813 static PyObject* top_eq = nullptr;
1814 if (!top_eq) {
1817 Py_DECREF(top_eq); // make it borrowed
1819 }
1821 }
1822
1823 if (HasAttrDirect(pyclass, PyStrings::gNe, true) && \
1824 Cppyy::GetMethodIndicesFromName(klass->fCppType, "__ne__").empty()) {
1826 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators();
1827 klass->fOperators->fNe = cppol;
1828 // re-insert the forwarding __ne__ (same reason as above for __eq__)
1829 static PyObject* top_ne = nullptr;
1830 if (!top_ne) {
1833 Py_DECREF(top_ne); // make it borrowed
1835 }
1837 }
1838
1839#if 0
1841 // guarantee that the result of __repr__ is a Python string
1842 Utility::AddToClass(pyclass, "__cpp_repr", "__repr__");
1844 }
1845
1847 // guarantee that the result of __str__ is a Python string
1848 Utility::AddToClass(pyclass, "__cpp_str", "__str__");
1850 }
1851#endif
1852
1853 if (Cppyy::IsAggregate(((CPPClass*)pyclass)->fCppType) && name.compare(0, 5, "std::", 5) != 0 &&
1854 name.compare(0, 6, "tuple<", 6) != 0) {
1855 // create a pseudo-constructor to allow initializer-style object creation
1856 Cppyy::TCppType_t kls = ((CPPClass*)pyclass)->fCppType;
1858 if (ndata) {
1859 std::string rname = name;
1861
1862 std::ostringstream initdef;
1863 initdef << "namespace __cppyy_internal {\n"
1864 << "void init_" << rname << "(" << name << "*& self";
1865 bool codegen_ok = true;
1866 std::vector<std::string> arg_types, arg_names, arg_defaults;
1867 arg_types.reserve(ndata); arg_names.reserve(ndata); arg_defaults.reserve(ndata);
1868 for (Cppyy::TCppIndex_t i = 0; i < ndata; ++i) {
1870 continue;
1871
1872 const std::string& txt = Cppyy::GetDatamemberType(kls, i);
1873 const std::string& res = Cppyy::IsEnum(txt) ? txt : Cppyy::ResolveName(txt);
1874 const std::string& cpd = TypeManip::compound(res);
1875 std::string res_clean = TypeManip::clean_type(res, false, true);
1876
1877 if (res_clean == "internal_enum_type_t")
1878 res_clean = txt; // restore (properly scoped name)
1879
1880 if (res.rfind(']') == std::string::npos && res.rfind(')') == std::string::npos) {
1881 if (!cpd.empty()) arg_types.push_back(res_clean+cpd);
1882 else arg_types.push_back("const "+res_clean+"&");
1883 arg_names.push_back(Cppyy::GetDatamemberName(kls, i));
1884 if ((!cpd.empty() && cpd.back() == '*') || Cppyy::IsBuiltin(res_clean))
1885 arg_defaults.push_back("0");
1886 else {
1889 }
1890 } else {
1891 codegen_ok = false; // TODO: how to support arrays, anonymous enums, etc?
1892 break;
1893 }
1894 }
1895
1896 if (codegen_ok && !arg_types.empty()) {
1897 bool defaults_ok = arg_defaults.size() == arg_types.size();
1898 for (std::vector<std::string>::size_type i = 0; i < arg_types.size(); ++i) {
1899 initdef << ", " << arg_types[i] << " " << arg_names[i];
1900 if (defaults_ok) initdef << " = " << arg_defaults[i];
1901 }
1902 initdef << ") {\n self = new " << name << "{";
1903 for (std::vector<std::string>::size_type i = 0; i < arg_names.size(); ++i) {
1904 if (i != 0) initdef << ", ";
1905 initdef << arg_names[i];
1906 }
1907 initdef << "};\n} }";
1908
1909 if (Cppyy::Compile(initdef.str(), true /* silent */)) {
1910 Cppyy::TCppScope_t cis = Cppyy::GetScope("__cppyy_internal");
1911 const auto& mix = Cppyy::GetMethodIndicesFromName(cis, "init_"+rname);
1912 if (mix.size()) {
1913 if (!Utility::AddToClass(pyclass, "__init__",
1914 new CPPFunction(cis, Cppyy::GetMethod(cis, mix[0]))))
1915 PyErr_Clear();
1916 }
1917 }
1918 }
1919 }
1920 }
1921
1922
1923//- class name based pythonization -------------------------------------------
1924
1925 if (IsTemplatedSTLClass(name, "span")) {
1926 // libstdc++ (GCC >= 15) implements std::span::iterator using a private
1927 // nested tag type, which makes the iterator non-instantiable by
1928 // CallFunc-generated wrappers (the return type cannot be named without
1929 // violating access rules).
1930 //
1931 // To preserve correct Python iteration semantics, we replace begin()/end()
1932 // for std::span to return a custom pointer-based iterator instead. This
1933 // avoids relying on std::span::iterator while still providing a real C++
1934 // iterator object that CPyCppyy can also wrap and expose via
1935 // __iter__/__next__.
1938 }
1939
1940 if (IsTemplatedSTLClass(name, "vector")) {
1941
1942 // std::vector<bool> is a special case in C++
1944 if (klass->fCppType == sVectorBoolTypeID) {
1947 } else {
1948 // constructor that takes python collections
1949 Utility::AddToClass(pyclass, "__real_init", "__init__");
1951
1952 // data with size
1953 Utility::AddToClass(pyclass, "__real_data", "data");
1955
1956 // The addition of the __array__ utility to std::vector Python proxies causes a
1957 // bug where the resulting array is a single dimension, causing loss of data when
1958 // converting to numpy arrays, for >1dim vectors. Since this C++ pythonization
1959 // was added with the upgrade in 6.32, and is only defined and used recursively,
1960 // the safe option is to disable this function and no longer add it.
1961#if 0
1962 // numpy array conversion
1964#endif
1965
1966 // checked getitem
1968 Utility::AddToClass(pyclass, "_getitem__unchecked", "__getitem__");
1970 }
1971
1972 // vector-optimized iterator protocol
1974
1975 // optimized __iadd__
1977
1978 // helpers for iteration
1979 const std::string& vtype = Cppyy::ResolveName(name+"::value_type");
1980 if (vtype.rfind("value_type") == std::string::npos) { // actually resolved?
1984 }
1985
1986 size_t typesz = Cppyy::SizeOf(name+"::value_type");
1987 if (typesz) {
1991 }
1992 }
1993 }
1994
1995 else if (IsTemplatedSTLClass(name, "array")) {
1996 // constructor that takes python associative collections
1997 Utility::AddToClass(pyclass, "__real_init", "__init__");
1999 }
2000
2001 else if (IsTemplatedSTLClass(name, "map") || IsTemplatedSTLClass(name, "unordered_map")) {
2002 // constructor that takes python associative collections
2003 Utility::AddToClass(pyclass, "__real_init", "__init__");
2005
2007 }
2008
2009 else if (IsTemplatedSTLClass(name, "set")) {
2010 // constructor that takes python associative collections
2011 Utility::AddToClass(pyclass, "__real_init", "__init__");
2013
2015 }
2016
2017 else if (IsTemplatedSTLClass(name, "pair")) {
2020 }
2021
2022 if (IsTemplatedSTLClass(name, "shared_ptr") || IsTemplatedSTLClass(name, "unique_ptr")) {
2023 Utility::AddToClass(pyclass, "__real_init", "__init__");
2025 }
2026
2027 else if (!((PyTypeObject*)pyclass)->tp_iter && \
2028 (name.find("iterator") != std::string::npos || gIteratorTypes.find(name) != gIteratorTypes.end())) {
2029 ((PyTypeObject*)pyclass)->tp_iternext = (iternextfunc)STLIterNext;
2033 }
2034
2035 else if (name == "string" || name == "std::string") { // TODO: ask backend as well
2044 Utility::AddToClass(pyclass, "__cpp_find", "find");
2046 Utility::AddToClass(pyclass, "__cpp_rfind", "rfind");
2048 Utility::AddToClass(pyclass, "__cpp_replace", "replace");
2051
2052 // to allow use of std::string in dictionaries and findable with str
2054 }
2055
2056 else if (name == "basic_string_view<char,char_traits<char> >" || name == "std::basic_string_view<char>") {
2057 Utility::AddToClass(pyclass, "__real_init", "__init__");
2065 }
2066
2067 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> >") {
2074 }
2075
2076 else if (name == "complex<double>" || name == "std::complex<double>") {
2077 Utility::AddToClass(pyclass, "__cpp_real", "real");
2079 Utility::AddToClass(pyclass, "__cpp_imag", "imag");
2083 }
2084
2085 else if (IsTemplatedSTLClass(name, "complex")) {
2086 Utility::AddToClass(pyclass, "__cpp_real", "real");
2088 Utility::AddToClass(pyclass, "__cpp_imag", "imag");
2092 }
2093
2094// direct user access; there are two calls here:
2095// - explicit pythonization: won't fall through to the base classes and is preferred if present
2096// - normal pythonization: only called if explicit isn't present, falls through to base classes
2097 bool bUserOk = true; PyObject* res = nullptr;
2101 bUserOk = (bool)res;
2102 } else {
2104 if (func) {
2105 res = PyObject_CallFunctionObjArgs(func, pyclass, pyname, nullptr);
2106 Py_DECREF(func);
2107 bUserOk = (bool)res;
2108 } else
2109 PyErr_Clear();
2110 }
2111 if (!bUserOk) {
2113 return false;
2114 } else {
2115 Py_XDECREF(res);
2116 // pyname handed to args tuple below
2117 }
2118
2119// call registered pythonizors, if any: first run the namespace-specific pythonizors, then
2120// the global ones (the idea is to allow writing a pythonizor that see all classes)
2121 bool pstatus = true;
2123 auto &pyzMap = pythonizations();
2124 if (!outer_scope.empty()) {
2125 auto p = pyzMap.find(outer_scope);
2126 if (p != pyzMap.end()) {
2128 name.substr(outer_scope.size()+2, std::string::npos).c_str());
2131 }
2132 }
2133
2134 if (pstatus) {
2135 auto p = pyzMap.find("");
2136 if (p != pyzMap.end())
2137 pstatus = run_pythonizors(pyclass, pyname, p->second);
2138 }
2139
2141
2142// phew! all done ...
2143 return pstatus;
2144}
#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
_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 * gCTypesType
Definition PyStrings.cxx:39
PyObject * gRealInit
Definition PyStrings.cxx:42
PyObject * gExPythonize
Definition PyStrings.cxx:72
PyObject * gLifeLine
Definition PyStrings.cxx:29
PyObject * gGetItem
Definition PyStrings.cxx:23
PyObject * gCppBool
Definition PyStrings.cxx:11
PyObject * gCppReal
Definition PyStrings.cxx:64
PyObject * gPythonize
Definition PyStrings.cxx:73
PyObject * gTypeCode
Definition PyStrings.cxx:38
PyObject * gPostInc
Definition PyStrings.cxx:18
PyObject * gCppImag
Definition PyStrings.cxx:65
PyObject * gValueSize
Definition PyStrings.cxx:62
PyObject * gSetItem
Definition PyStrings.cxx:25
PyObject * gGetNoCheck
Definition PyStrings.cxx:24
PyObject * gCppRepr
Definition PyStrings.cxx:35
PyObject * gValueType
Definition PyStrings.cxx:61
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:813
bool AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Definition Utility.cxx:186
PyTypeObject VectorIter_Type
PyObject * GetScopeProxy(Cppyy::TCppScope_t)
static PyObject * GetAttrDirect(PyObject *pyclass, PyObject *pyname)
bool Pythonize(PyObject *pyclass, const std::string &name)
bool CPPOverload_Check(T *object)
Definition CPPOverload.h:90
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:24
RPY_EXPORTED size_t SizeOf(TCppType_t klass)
intptr_t TCppMethod_t
Definition cpp_cppyy.h:22
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 TCppScope_t gGlobalScope
Definition cpp_cppyy.h:53
RPY_EXPORTED std::string ResolveName(const std::string &cppitem_name)
TCppScope_t TCppType_t
Definition cpp_cppyy.h:19
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:18
RPY_EXPORTED std::string GetMethodResultType(TCppMethod_t)
RPY_EXPORTED std::string GetDatamemberName(TCppScope_t scope, TCppIndex_t idata)