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
320static bool FillVector(PyObject* vecin, PyObject* args, ItemGetter* getter)
321{
322 Py_ssize_t sz = getter->size();
323 if (sz < 0)
324 return false;
325
326// reserve memory as applicable
327 if (0 < sz) {
328 PyObject* res = PyObject_CallMethod(vecin, (char*)"reserve", (char*)"n", sz);
329 Py_DECREF(res);
330 } else // i.e. sz == 0, so empty container: done
331 return true;
332
333 bool fill_ok = true;
334
335// two main options: a list of lists (or tuples), or a list of objects; the former
336// are emplace_back'ed, the latter push_back'ed
338 if (!fi) PyErr_Clear();
340 // use emplace_back to construct the vector entries one by one
341 PyObject* eb_call = PyObject_GetAttrString(vecin, (char*)"emplace_back");
343 bool value_is_vector = false;
345 // if the value_type is a vector, then allow for initialization from sequences
346 if (std::string(CPyCppyy_PyText_AsString(vtype)).rfind("std::vector", 0) != std::string::npos)
347 value_is_vector = true;
348 } else
349 PyErr_Clear();
351
352 if (eb_call) {
354 for (int i = 0; /* until break */; ++i) {
355 PyObject* item = getter->get();
356 if (item) {
358 eb_args = PyTuple_New(1);
360 } else if (PyTuple_CheckExact(item)) {
361 eb_args = item;
362 } else if (PyList_CheckExact(item)) {
365 for (Py_ssize_t j = 0; j < isz; ++j) {
369 }
371 } else {
373 PyErr_Format(PyExc_TypeError, "argument %d is not a tuple or list", i);
374 fill_ok = false;
375 break;
376 }
379 if (!ebres) {
380 fill_ok = false;
381 break;
382 }
384 } else {
385 if (PyErr_Occurred()) {
388 fill_ok = false;
389 else { PyErr_Clear(); }
390 }
391 break;
392 }
393 }
395 }
396 } else {
397 // use push_back to add the vector entries one by one
398 PyObject* pb_call = PyObject_GetAttrString(vecin, (char*)"push_back");
399 if (pb_call) {
400 for (;;) {
401 PyObject* item = getter->get();
402 if (item) {
405 if (!pbres) {
406 fill_ok = false;
407 break;
408 }
410 } else {
411 if (PyErr_Occurred()) {
414 fill_ok = false;
415 else { PyErr_Clear(); }
416 }
417 break;
418 }
419 }
421 }
422 }
423 Py_XDECREF(fi);
424
425 return fill_ok;
426}
427
428PyObject* VectorIAdd(PyObject* self, PyObject* args, PyObject* /* kwds */)
429{
430// Implement fast __iadd__ on std::vector (generic __iadd__ is in Python)
431 ItemGetter* getter = GetGetter(args);
432
433 if (getter) {
434 bool fill_ok = FillVector(self, args, getter);
435 delete getter;
436
437 if (!fill_ok)
438 return nullptr;
439
441 return self;
442 }
443
444// if no getter, it could still be b/c we have a buffer (e.g. numpy); looping over
445// a buffer here is slow, so use insert() instead
446 if (PyTuple_GET_SIZE(args) == 1) {
447 PyObject* fi = PyTuple_GET_ITEM(args, 0);
450 if (vend) {
451 // when __iadd__ is overriden, the operation does not end with
452 // calling the __iadd__ method, but also assigns the result to the
453 // lhs of the iadd. For example, performing vec += arr, Python
454 // first calls our override, and then does vec = vec.iadd(arr).
457
458 if (!it)
459 return nullptr;
460
461 Py_DECREF(it);
462 // Assign the result of the __iadd__ override to the std::vector
464 return self;
465 }
466 }
467 }
468
469 if (!PyErr_Occurred())
470 PyErr_SetString(PyExc_TypeError, "argument is not iterable");
471 return nullptr; // error already set
472}
473
474
475PyObject* VectorInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
476{
477// Specialized vector constructor to allow construction from containers; allowing
478// such construction from initializer_list instead would possible, but can be
479// error-prone. This use case is common enough for std::vector to implement it
480// directly, except for arrays (which can be passed wholesale) and strings (which
481// won't convert properly as they'll be seen as buffers)
482
483 ItemGetter* getter = GetGetter(args);
484
485 if (getter) {
486 // construct an empty vector, then back-fill it
488 if (!result) {
489 delete getter;
490 return nullptr;
491 }
492
493 bool fill_ok = FillVector(self, args, getter);
494 delete getter;
495
496 if (!fill_ok) {
498 return nullptr;
499 }
500
501 return result;
502 }
503
504// The given argument wasn't iterable: simply forward to regular constructor
506 if (realInit) {
507 PyObject* result = PyObject_Call(realInit, args, nullptr);
509 return result;
510 }
511
512 return nullptr;
513}
514
515//---------------------------------------------------------------------------
517{
518 PyObject* pydata = CallPyObjMethod(self, "__real_data");
520 return pydata;
521
523 if (!pylen) {
524 PyErr_Clear();
525 return pydata;
526 }
527
528 long clen = PyInt_AsLong(pylen);
530
532 ((CPPInstance*)pydata)->CastToArray(clen);
533 return pydata;
534 }
535
536 ((LowLevelView*)pydata)->resize((size_t)clen);
537 return pydata;
538}
539
540
541// This function implements __array__, added to std::vector python proxies and causes
542// a bug (see explanation at Utility::AddToClass(pyclass, "__array__"...) in CPyCppyy::Pythonize)
543// The recursive nature of this function, passes each subarray (pydata) to the next call and only
544// the final buffer is cast to a lowlevel view and resized (in VectorData), resulting in only the
545// first 1D array to be returned. See https://github.com/root-project/root/issues/17729
546// It is temporarily removed to prevent errors due to -Wunused-function, since it is no longer added.
547#if 0
548//---------------------------------------------------------------------------
550{
551 PyObject* pydata = VectorData(self, nullptr);
556 return newarr;
557}
558#endif
559
560//-----------------------------------------------------------------------------
561static PyObject* vector_iter(PyObject* v) {
563 if (!vi) return nullptr;
564
565 Py_INCREF(v);
566 vi->ii_container = v;
567
568// tell the iterator code to set a life line if this container is a temporary
569 vi->vi_flags = vectoriterobject::kDefault;
570 if (Py_REFCNT(v) <= 2 || (((CPPInstance*)v)->fFlags & CPPInstance::kIsValue))
572
574 if (pyvalue_type) {
576 if (pyvalue_size) {
577 vi->vi_stride = PyLong_AsLong(pyvalue_size);
579 } else {
580 PyErr_Clear();
581 vi->vi_stride = 0;
582 }
583
585 std::string value_type = CPyCppyy_PyText_AsString(pyvalue_type);
586 value_type = Cppyy::ResolveName(value_type);
587 vi->vi_klass = Cppyy::GetScope(value_type);
588 if (!vi->vi_klass) {
589 // look for a special case of pointer to a class type (which is a builtin, but it
590 // is more useful to treat it polymorphically by allowing auto-downcasts)
591 const std::string& clean_type = TypeManip::clean_type(value_type, false, false);
593 if (c && TypeManip::compound(value_type) == "*") {
594 vi->vi_klass = c;
596 }
597 }
598 if (vi->vi_klass) {
599 vi->vi_converter = nullptr;
600 if (!vi->vi_flags) {
601 if (value_type.back() != '*') // meaning, object stored by-value
603 }
604 } else
605 vi->vi_converter = CPyCppyy::CreateConverter(value_type);
606 if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(value_type);
607
608 } else if (CPPScope_Check(pyvalue_type)) {
609 vi->vi_klass = ((CPPClass*)pyvalue_type)->fCppType;
610 vi->vi_converter = nullptr;
611 if (!vi->vi_stride) vi->vi_stride = Cppyy::SizeOf(vi->vi_klass);
612 if (!vi->vi_flags) vi->vi_flags = vectoriterobject::kNeedLifeLine;
613 }
614
615 PyObject* pydata = CallPyObjMethod(v, "__real_data");
616 if (!pydata || Utility::GetBuffer(pydata, '*', 1, vi->vi_data, false) == 0)
617 vi->vi_data = CPPInstance_Check(pydata) ? ((CPPInstance*)pydata)->GetObjectRaw() : nullptr;
619
620 } else {
621 PyErr_Clear();
622 vi->vi_data = nullptr;
623 vi->vi_stride = 0;
624 vi->vi_converter = nullptr;
625 vi->vi_klass = 0;
626 vi->vi_flags = 0;
627 }
628
630
631 vi->ii_pos = 0;
632 vi->ii_len = PySequence_Size(v);
633
635 return (PyObject*)vi;
636}
637
639{
640// Implement python's __getitem__ for std::vector<>s.
641 if (PySlice_Check(index)) {
642 if (!self->GetObject()) {
643 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
644 return nullptr;
645 }
646
649
650 start, stop, step;
652
654 if (!AdjustSlice(nlen, start, stop, step))
655 return nseq;
656
657 const Py_ssize_t sign = step < 0 ? -1 : 1;
658 for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
661 CallPyObjMethod(nseq, "push_back", item);
664 }
665
666 return nseq;
667 }
668
670}
671
672
674
676{
677// std::vector<bool> is a special-case in C++, and its return type depends on
678// the compiler: treat it special here as well
679 if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
681 "require object of type std::vector<bool>, but %s given",
682 Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
683 return nullptr;
684 }
685
686 if (!self->GetObject()) {
687 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
688 return nullptr;
689 }
690
691 if (PySlice_Check(idx)) {
694
695 start, stop, step;
698 if (!AdjustSlice(nlen, start, stop, step))
699 return nseq;
700
701 const Py_ssize_t sign = step < 0 ? -1 : 1;
702 for (Py_ssize_t i = start; i*sign < stop*sign; i += step) {
705 CallPyObjMethod(nseq, "push_back", item);
708 }
709
710 return nseq;
711 }
712
714 if (!pyindex)
715 return nullptr;
716
719
720// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
721 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
722
723// finally, return the value
724 if (bool((*vb)[index]))
727}
728
730{
731// std::vector<bool> is a special-case in C++, and its return type depends on
732// the compiler: treat it special here as well
733 if (!CPPInstance_Check(self) || self->ObjectIsA() != sVectorBoolTypeID) {
735 "require object of type std::vector<bool>, but %s given",
736 Cppyy::GetScopedFinalName(self->ObjectIsA()).c_str());
737 return nullptr;
738 }
739
740 if (!self->GetObject()) {
741 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
742 return nullptr;
743 }
744
745 int bval = 0; PyObject* idx = nullptr;
746 if (!PyArg_ParseTuple(args, const_cast<char*>("Oi:__setitem__"), &idx, &bval))
747 return nullptr;
748
750 if (!pyindex)
751 return nullptr;
752
755
756// get hold of the actual std::vector<bool> (no cast, as vector is never a base)
757 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
758
759// finally, set the value
760 (*vb)[index] = (bool)bval;
761
763}
764
765
766//- array behavior as primitives ----------------------------------------------
767PyObject* ArrayInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
768{
769// std::array is normally only constructed using aggregate initialization, which
770// is a concept that does not exist in python, so use this custom constructor to
771// to fill the array using setitem
772
773 if (args && PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0))) {
774 // construct the empty array, then fill it
776 if (!result)
777 return nullptr;
778
779 PyObject* items = PyTuple_GET_ITEM(args, 0);
781 if (PySequence_Size(self) != fillsz) {
782 PyErr_Format(PyExc_ValueError, "received sequence of size %zd where %zd expected",
785 return nullptr;
786 }
787
789 for (Py_ssize_t i = 0; i < fillsz; ++i) {
795 if (!sires) {
798 return nullptr;
799 } else
801 }
803
804 return result;
805 } else
806 PyErr_Clear();
807
808// The given argument wasn't iterable: simply forward to regular constructor
810 if (realInit) {
811 PyObject* result = PyObject_Call(realInit, args, nullptr);
813 return result;
814 }
815
816 return nullptr;
817}
818
819
820//- map behavior as primitives ------------------------------------------------
822{
823// construct an empty map, then fill it with the key, value pairs
825 if (!result)
826 return nullptr;
827
829 for (Py_ssize_t i = 0; i < PySequence_Size(pairs); ++i) {
831 PyObject* sires = nullptr;
832 if (pair && PySequence_Check(pair) && PySequence_Size(pair) == 2) {
833 PyObject* key = PySequence_GetItem(pair, 0);
837 Py_DECREF(key);
838 }
839 Py_DECREF(pair);
840 if (!sires) {
843 if (!PyErr_Occurred())
844 PyErr_SetString(PyExc_TypeError, "Failed to fill map (argument not a dict or sequence of pairs)");
845 return nullptr;
846 } else
848 }
850
851 return result;
852}
853
854PyObject* MapInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
855{
856// Specialized map constructor to allow construction from mapping containers and
857// from tuples of pairs ("initializer_list style").
858
859// PyMapping_Check is not very discriminatory, as it basically only checks for the
860// existence of __getitem__, hence the most common cases of tuple and list are
861// dropped straight-of-the-bat (the PyMapping_Items call will fail on them).
862 if (PyTuple_GET_SIZE(args) == 1 && PyMapping_Check(PyTuple_GET_ITEM(args, 0)) && \
864 PyObject* assoc = PyTuple_GET_ITEM(args, 0);
865#if PY_VERSION_HEX < 0x03000000
866 // to prevent warning about literal string, expand macro
867 PyObject* items = PyObject_CallMethod(assoc, (char*)"items", nullptr);
868#else
869 // in p3, PyMapping_Items isn't a macro, but a function that short-circuits dict
871#endif
872 if (items && PySequence_Check(items)) {
875 return result;
876 }
877
879 PyErr_Clear();
880
881 // okay to fall through as long as 'self' has not been created (is done in MapFromPairs)
882 }
883
884// tuple of pairs case (some mapping types are sequences)
885 if (PyTuple_GET_SIZE(args) == 1 && PySequence_Check(PyTuple_GET_ITEM(args, 0)))
886 return MapFromPairs(self, PyTuple_GET_ITEM(args, 0));
887
888// The given argument wasn't a mapping or tuple of pairs: forward to regular constructor
890 if (realInit) {
891 PyObject* result = PyObject_Call(realInit, args, nullptr);
893 return result;
894 }
895
896 return nullptr;
897}
898
900{
901// Implement python's __contains__ for std::map/std::set
902 PyObject* result = nullptr;
903
904 PyObject* iter = CallPyObjMethod(self, "find", obj);
905 if (CPPInstance_Check(iter)) {
906 PyStrings::gEnd);
907 if (CPPInstance_Check(end)) {
908 if (!PyObject_RichCompareBool(iter, end, Py_EQ)) {
910 result = Py_True;
911 }
912 }
913 Py_XDECREF(end);
914 }
915 Py_XDECREF(iter);
916
917 if (!result) {
918 PyErr_Clear(); // e.g. wrong argument type, which should always lead to False
921 }
922
923 return result;
924}
925
926
927//- set behavior as primitives ------------------------------------------------
928PyObject* SetInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
929{
930// Specialized set constructor to allow construction from Python sets.
931 if (PyTuple_GET_SIZE(args) == 1 && PySet_Check(PyTuple_GET_ITEM(args, 0))) {
932 PyObject* pyset = PyTuple_GET_ITEM(args, 0);
933
934 // construct an empty set, then fill it
936 if (!result)
937 return nullptr;
938
940 if (iter) {
941 PyObject* ins_call = PyObject_GetAttrString(self, (char*)"insert");
942
943 IterItemGetter getter{iter};
944 Py_DECREF(iter);
945
946 PyObject* item = getter.get();
947 while (item) {
950 if (!insres) {
953 return nullptr;
954 } else
956 item = getter.get();
957 }
959 }
960
961 return result;
962 }
963
964// The given argument wasn't iterable: simply forward to regular constructor
966 if (realInit) {
967 PyObject* result = PyObject_Call(realInit, args, nullptr);
969 return result;
970 }
971
972 return nullptr;
973}
974
975
976//- STL container iterator support --------------------------------------------
977static const ptrdiff_t PS_END_ADDR = 7; // non-aligned address, so no clash
978static const ptrdiff_t PS_FLAG_ADDR = 11; // id.
979static const ptrdiff_t PS_COLL_ADDR = 13; // id.
980
982{
983// Implement python's __iter__ for low level views used through STL-type begin()/end()
985
986 if (LowLevelView_Check(iter)) {
987 // builtin pointer iteration: can only succeed if a size is available
989 if (sz == -1) {
990 Py_DECREF(iter);
991 return nullptr;
992 }
993 PyObject* lliter = Py_TYPE(iter)->tp_iter(iter);
994 ((indexiterobject*)lliter)->ii_len = sz;
995 Py_DECREF(iter);
996 return lliter;
997 }
998
999 if (iter) {
1000 Py_DECREF(iter);
1001 PyErr_SetString(PyExc_TypeError, "unrecognized iterator type for low level views");
1002 }
1003
1004 return nullptr;
1005}
1006
1008{
1009// Implement python's __iter__ for std::iterator<>s
1011 if (iter) {
1012 PyStrings::gEnd);
1013 if (end) {
1014 if (CPPInstance_Check(iter)) {
1015 // use the data member cache to store extra state on the iterator object,
1016 // without it being visible on the Python side
1017 auto& dmc = ((CPPInstance*)iter)->GetDatamemberCache();
1018 dmc.push_back(std::make_pair(PS_END_ADDR, end));
1019
1020 // set a flag, indicating first iteration (reset in __next__)
1022 dmc.push_back(std::make_pair(PS_FLAG_ADDR, Py_False));
1023
1024 // make sure the iterated over collection remains alive for the duration
1025 Py_INCREF(self);
1026 dmc.push_back(std::make_pair(PS_COLL_ADDR, self));
1027 } else {
1028 // could store "end" on the object's dictionary anyway, but if end() returns
1029 // a user-customized object, then its __next__ is probably custom, too
1030 Py_DECREF(end);
1031 }
1032 }
1033 }
1034 return iter;
1035}
1036
1037//- generic iterator support over a sequence with operator[] and size ---------
1038//-----------------------------------------------------------------------------
1039static PyObject* index_iter(PyObject* c) {
1041 if (!ii) return nullptr;
1042
1043 Py_INCREF(c);
1044 ii->ii_container = c;
1045 ii->ii_pos = 0;
1046 ii->ii_len = PySequence_Size(c);
1047
1049 return (PyObject*)ii;
1050}
1051
1052
1053//- safe indexing for STL-like vector w/o iterator dictionaries ---------------
1054/* replaced by indexiterobject iteration, but may still have some future use ...
1055PyObject* CheckedGetItem(PyObject* self, PyObject* obj)
1056{
1057// Implement a generic python __getitem__ for STL-like classes that are missing the
1058// reflection info for their iterators. This is then used for iteration by means of
1059// consecutive indices, it such index is of integer type.
1060 Py_ssize_t size = PySequence_Size(self);
1061 Py_ssize_t idx = PyInt_AsSsize_t(obj);
1062 if ((size == (Py_ssize_t)-1 || idx == (Py_ssize_t)-1) && PyErr_Occurred()) {
1063 // argument conversion problem: let method itself resolve anew and report
1064 PyErr_Clear();
1065 return PyObject_CallMethodOneArg(self, PyStrings::gGetNoCheck, obj);
1066 }
1067
1068 bool inbounds = false;
1069 if (idx < 0) idx += size;
1070 if (0 <= idx && 0 <= size && idx < size)
1071 inbounds = true;
1072
1073 if (inbounds)
1074 return PyObject_CallMethodOneArg(self, PyStrings::gGetNoCheck, obj);
1075 else
1076 PyErr_SetString( PyExc_IndexError, "index out of range" );
1077
1078 return nullptr;
1079}*/
1080
1081
1082//- pair as sequence to allow tuple unpacking --------------------------------
1084{
1085// For std::map<> iteration, unpack std::pair<>s into tuples for the loop.
1086 long idx = PyLong_AsLong(pyindex);
1087 if (idx == -1 && PyErr_Occurred())
1088 return nullptr;
1089
1090 if (!CPPInstance_Check(self) || !((CPPInstance*)self)->GetObject()) {
1091 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
1092 return nullptr;
1093 }
1094
1095 if ((int)idx == 0)
1097 else if ((int)idx == 1)
1099
1100// still here? Trigger stop iteration
1101 PyErr_SetString(PyExc_IndexError, "out of bounds");
1102 return nullptr;
1103}
1104
1105//- simplistic len() functions -----------------------------------------------
1107 return PyInt_FromLong(2);
1108}
1109
1110
1111//- shared/unique_ptr behavior -----------------------------------------------
1112PyObject* SmartPtrInit(PyObject* self, PyObject* args, PyObject* /* kwds */)
1113{
1114// since the shared/unique pointer will take ownership, we need to relinquish it
1116 if (realInit) {
1117 PyObject* result = PyObject_Call(realInit, args, nullptr);
1119 if (result && PyTuple_GET_SIZE(args) == 1 && CPPInstance_Check(PyTuple_GET_ITEM(args, 0))) {
1121 if (!(cppinst->fFlags & CPPInstance::kIsSmartPtr)) cppinst->CppOwns();
1122 }
1123 return result;
1124 }
1125 return nullptr;
1126}
1127
1128
1129//- string behavior as primitives --------------------------------------------
1130#if PY_VERSION_HEX >= 0x03000000
1131// TODO: this is wrong, b/c it doesn't order
1134}
1135#endif
1136static inline
1137PyObject* CPyCppyy_PyString_FromCppString(std::string_view s, bool native=true) {
1138 if (native)
1139 return PyBytes_FromStringAndSize(s.data(), s.size());
1140 return CPyCppyy_PyText_FromStringAndSize(s.data(), s.size());
1141}
1142
1143static inline
1144PyObject* CPyCppyy_PyString_FromCppString(std::wstring_view s, bool native=true) {
1145 PyObject* pyobj = PyUnicode_FromWideChar(s.data(), s.size());
1146 if (pyobj && native) {
1147 PyObject* pybytes = PyUnicode_AsEncodedString(pyobj, "UTF-8", "strict");
1149 pyobj = pybytes;
1150 }
1151 return pyobj;
1152}
1153
1154#define CPPYY_IMPL_STRING_PYTHONIZATION(type, name) \
1155static inline \
1156PyObject* name##StringGetData(PyObject* self, bool native=true) \
1157{ \
1158 if (CPyCppyy::CPPInstance_Check(self)) { \
1159 type* obj = ((type*)((CPPInstance*)self)->GetObject()); \
1160 if (obj) return CPyCppyy_PyString_FromCppString(*obj, native); \
1161 } \
1162 PyErr_Format(PyExc_TypeError, "object mismatch (%s expected)", #type); \
1163 return nullptr; \
1164} \
1165 \
1166PyObject* name##StringStr(PyObject* self) \
1167{ \
1168 PyObject* pyobj = name##StringGetData(self, false); \
1169 if (!pyobj) { \
1170 /* do a native conversion to make printing possible (debatable) */ \
1171 PyErr_Clear(); \
1172 PyObject* pybytes = name##StringGetData(self, true); \
1173 if (pybytes) { /* should not fail */ \
1174 pyobj = PyObject_Str(pybytes); \
1175 Py_DECREF(pybytes); \
1176 } \
1177 } \
1178 return pyobj; \
1179} \
1180 \
1181PyObject* name##StringBytes(PyObject* self) \
1182{ \
1183 return name##StringGetData(self, true); \
1184} \
1185 \
1186PyObject* name##StringRepr(PyObject* self) \
1187{ \
1188 PyObject* data = name##StringGetData(self, true); \
1189 if (data) { \
1190 PyObject* repr = PyObject_Repr(data); \
1191 Py_DECREF(data); \
1192 return repr; \
1193 } \
1194 return nullptr; \
1195} \
1196 \
1197PyObject* name##StringIsEqual(PyObject* self, PyObject* obj) \
1198{ \
1199 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1200 if (data) { \
1201 PyObject* result = PyObject_RichCompare(data, obj, Py_EQ); \
1202 Py_DECREF(data); \
1203 return result; \
1204 } \
1205 return nullptr; \
1206} \
1207 \
1208PyObject* name##StringIsNotEqual(PyObject* self, PyObject* obj) \
1209{ \
1210 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1211 if (data) { \
1212 PyObject* result = PyObject_RichCompare(data, obj, Py_NE); \
1213 Py_DECREF(data); \
1214 return result; \
1215 } \
1216 return nullptr; \
1217}
1218
1219// Only define STLStringCompare:
1220#define CPPYY_IMPL_STRING_PYTHONIZATION_CMP(type, name) \
1221CPPYY_IMPL_STRING_PYTHONIZATION(type, name) \
1222PyObject* name##StringCompare(PyObject* self, PyObject* obj) \
1223{ \
1224 PyObject* data = name##StringGetData(self, PyBytes_Check(obj)); \
1225 int result = 0; \
1226 if (data) { \
1227 result = PyObject_Compare(data, obj); \
1228 Py_DECREF(data); \
1229 } \
1230 if (PyErr_Occurred()) \
1231 return nullptr; \
1232 return PyInt_FromLong(result); \
1233}
1234
1238
1239static inline std::string* GetSTLString(CPPInstance* self) {
1240 if (!CPPInstance_Check(self)) {
1241 PyErr_SetString(PyExc_TypeError, "std::string object expected");
1242 return nullptr;
1243 }
1244
1245 std::string* obj = (std::string*)self->GetObject();
1246 if (!obj)
1247 PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
1248
1249 return obj;
1250}
1251
1253{
1254 std::string* obj = GetSTLString(self);
1255 if (!obj)
1256 return nullptr;
1257
1258 char* keywords[] = {(char*)"encoding", (char*)"errors", (char*)nullptr};
1259 const char* encoding = nullptr; const char* errors = nullptr;
1261 const_cast<char*>("s|s"), keywords, &encoding, &errors))
1262 return nullptr;
1263
1264 return PyUnicode_Decode(obj->data(), obj->size(), encoding, errors);
1265}
1266
1268{
1269 std::string* obj = GetSTLString(self);
1270 if (!obj)
1271 return nullptr;
1272
1273 const char* needle = CPyCppyy_PyText_AsString(pyobj);
1274 if (!needle)
1275 return nullptr;
1276
1277 if (obj->find(needle) != std::string::npos) {
1279 }
1280
1282}
1283
1285{
1286 std::string* obj = GetSTLString(self);
1287 if (!obj)
1288 return nullptr;
1289
1290// both str and std::string have a method "replace", but the Python version only
1291// accepts strings and takes no keyword arguments, whereas the C++ version has no
1292// overload that takes a string
1293
1294 if (2 <= PyTuple_GET_SIZE(args) && CPyCppyy_PyText_Check(PyTuple_GET_ITEM(args, 0))) {
1295 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());
1296 PyObject* meth = PyObject_GetAttrString(pystr, (char*)"replace");
1299 Py_DECREF(meth);
1300 return result;
1301 }
1302
1303 PyObject* cppreplace = PyObject_GetAttrString((PyObject*)self, (char*)"__cpp_replace");
1304 if (cppreplace) {
1305 PyObject* result = PyObject_Call(cppreplace, args, nullptr);
1307 return result;
1308 }
1309
1310 PyErr_SetString(PyExc_AttributeError, "\'std::string\' object has no attribute \'replace\'");
1311 return nullptr;
1312}
1313
1314#define CPYCPPYY_STRING_FINDMETHOD(name, cppname, pyname) \
1315PyObject* STLString##name(CPPInstance* self, PyObject* args, PyObject* /*kwds*/) \
1316{ \
1317 std::string* obj = GetSTLString(self); \
1318 if (!obj) \
1319 return nullptr; \
1320 \
1321 PyObject* cppmeth = PyObject_GetAttrString((PyObject*)self, (char*)#cppname);\
1322 if (cppmeth) { \
1323 PyObject* result = PyObject_Call(cppmeth, args, nullptr); \
1324 Py_DECREF(cppmeth); \
1325 if (result) { \
1326 if (PyLongOrInt_AsULong64(result) == (PY_ULONG_LONG)std::string::npos) {\
1327 Py_DECREF(result); \
1328 return PyInt_FromLong(-1); \
1329 } \
1330 return result; \
1331 } \
1332 PyErr_Clear(); \
1333 } \
1334 \
1335 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());\
1336 PyObject* pymeth = PyObject_GetAttrString(pystr, (char*)#pyname); \
1337 Py_DECREF(pystr); \
1338 PyObject* result = PyObject_CallObject(pymeth, args); \
1339 Py_DECREF(pymeth); \
1340 return result; \
1341}
1342
1343// both str and std::string have method "find" and "rfin"; try the C++ version first
1344// and fall back on the Python one in case of failure
1347
1349{
1350 std::string* obj = GetSTLString(self);
1351 if (!obj)
1352 return nullptr;
1353
1354 PyObject* pystr = CPyCppyy_PyText_FromStringAndSize(obj->data(), obj->size());
1357 return attr;
1358}
1359
1360
1361#if 0
1363{
1364// force C++ string types conversion to Python str per Python __repr__ requirements
1366 if (!res || CPyCppyy_PyText_Check(res))
1367 return res;
1369 Py_DECREF(res);
1370 return str_res;
1371}
1372
1374{
1375// force C++ string types conversion to Python str per Python __str__ requirements
1377 if (!res || CPyCppyy_PyText_Check(res))
1378 return res;
1380 Py_DECREF(res);
1381 return str_res;
1382}
1383#endif
1384
1386{
1387// std::string objects hash to the same values as Python strings to allow
1388// matches in dictionaries etc.
1391 Py_DECREF(data);
1392 return h;
1393}
1394
1395
1396//- string_view behavior as primitive ----------------------------------------
1398{
1399// if constructed from a Python unicode object, the constructor will convert it
1400// to a temporary byte string, which is likely to go out of scope too soon; so
1401// buffer it as needed
1403 if (realInit) {
1404 PyObject *strbuf = nullptr, *newArgs = nullptr;
1405 if (PyTuple_GET_SIZE(args) == 1) {
1406 PyObject* arg0 = PyTuple_GET_ITEM(args, 0);
1407 if (PyUnicode_Check(arg0)) {
1408 // convert to the expected bytes array to control the temporary
1409 strbuf = PyUnicode_AsEncodedString(arg0, "UTF-8", "strict");
1410 newArgs = PyTuple_New(1);
1413 } else if (PyBytes_Check(arg0)) {
1414 // tie the life time of the provided string to the string_view
1415 Py_INCREF(arg0);
1416 strbuf = arg0;
1417 }
1418 }
1419
1420 PyObject* result = PyObject_Call(realInit, newArgs ? newArgs : args, nullptr);
1421
1424
1425 // if construction was successful and a string buffer was used, add a
1426 // life line to it from the string_view bound object
1427 if (result && self && strbuf)
1430
1431 return result;
1432 }
1433 return nullptr;
1434}
1435
1436
1437//- STL iterator behavior ----------------------------------------------------
1439{
1440// Python iterator protocol __next__ for STL forward iterators.
1441 bool mustIncrement = true;
1442 PyObject* last = nullptr;
1443 if (CPPInstance_Check(self)) {
1444 auto& dmc = ((CPPInstance*)self)->GetDatamemberCache();
1445 for (auto& p: dmc) {
1446 if (p.first == PS_END_ADDR) {
1447 last = p.second;
1448 Py_INCREF(last);
1449 } else if (p.first == PS_FLAG_ADDR) {
1450 mustIncrement = p.second == Py_True;
1451 if (!mustIncrement) {
1452 Py_DECREF(p.second);
1454 p.second = Py_True;
1455 }
1456 }
1457 }
1458 }
1459
1460 PyObject* next = nullptr;
1461 if (last) {
1462 // handle special case of empty container (i.e. self is end)
1463 if (!PyObject_RichCompareBool(last, self, Py_EQ)) {
1464 bool iter_valid = true;
1465 if (mustIncrement) {
1466 // prefer preinc, but allow post-inc; in both cases, it is "self" that has
1467 // the updated state to dereference
1469 if (!iter) {
1470 PyErr_Clear();
1471 static PyObject* dummy = PyInt_FromLong(1l);
1473 }
1475 Py_XDECREF(iter);
1476 }
1477
1478 if (iter_valid) {
1480 if (!next) PyErr_Clear();
1481 }
1482 }
1483 Py_DECREF(last);
1484 }
1485
1486 if (!next) PyErr_SetString(PyExc_StopIteration, "");
1487 return next;
1488}
1489
1490
1491//- STL complex<T> behavior --------------------------------------------------
1492#define COMPLEX_METH_GETSET(name, cppname) \
1493static PyObject* name##ComplexGet(PyObject* self, void*) { \
1494 return PyObject_CallMethodNoArgs(self, cppname); \
1495} \
1496static int name##ComplexSet(PyObject* self, PyObject* value, void*) { \
1497 PyObject* result = PyObject_CallMethodOneArg(self, cppname, value); \
1498 if (result) { \
1499 Py_DECREF(result); \
1500 return 0; \
1501 } \
1502 return -1; \
1503} \
1504PyGetSetDef name##Complex{(char*)#name, (getter)name##ComplexGet, (setter)name##ComplexSet, nullptr, nullptr};
1505
1508
1511 if (!real) return nullptr;
1512 double r = PyFloat_AsDouble(real);
1513 Py_DECREF(real);
1514 if (r == -1. && PyErr_Occurred())
1515 return nullptr;
1516
1518 if (!imag) return nullptr;
1519 double i = PyFloat_AsDouble(imag);
1520 Py_DECREF(imag);
1521 if (i == -1. && PyErr_Occurred())
1522 return nullptr;
1523
1524 return PyComplex_FromDoubles(r, i);
1525}
1526
1529 if (!real) return nullptr;
1530 double r = PyFloat_AsDouble(real);
1531 Py_DECREF(real);
1532 if (r == -1. && PyErr_Occurred())
1533 return nullptr;
1534
1536 if (!imag) return nullptr;
1537 double i = PyFloat_AsDouble(imag);
1538 Py_DECREF(imag);
1539 if (i == -1. && PyErr_Occurred())
1540 return nullptr;
1541
1542 std::ostringstream s;
1543 s << '(' << r << '+' << i << "j)";
1544 return CPyCppyy_PyText_FromString(s.str().c_str());
1545}
1546
1548{
1549 return PyFloat_FromDouble(((std::complex<double>*)self->GetObject())->real());
1550}
1551
1552static int ComplexDRealSet(CPPInstance* self, PyObject* value, void*)
1553{
1554 double d = PyFloat_AsDouble(value);
1555 if (d == -1.0 && PyErr_Occurred())
1556 return -1;
1557 ((std::complex<double>*)self->GetObject())->real(d);
1558 return 0;
1559}
1560
1561PyGetSetDef ComplexDReal{(char*)"real", (getter)ComplexDRealGet, (setter)ComplexDRealSet, nullptr, nullptr};
1562
1563
1565{
1566 return PyFloat_FromDouble(((std::complex<double>*)self->GetObject())->imag());
1567}
1568
1569static int ComplexDImagSet(CPPInstance* self, PyObject* value, void*)
1570{
1571 double d = PyFloat_AsDouble(value);
1572 if (d == -1.0 && PyErr_Occurred())
1573 return -1;
1574 ((std::complex<double>*)self->GetObject())->imag(d);
1575 return 0;
1576}
1577
1578PyGetSetDef ComplexDImag{(char*)"imag", (getter)ComplexDImagGet, (setter)ComplexDImagSet, nullptr, nullptr};
1579
1581{
1582 double r = ((std::complex<double>*)self->GetObject())->real();
1583 double i = ((std::complex<double>*)self->GetObject())->imag();
1584 return PyComplex_FromDoubles(r, i);
1585}
1586
1587
1588} // unnamed namespace
1589
1590
1591//- public functions ---------------------------------------------------------
1592namespace CPyCppyy {
1593 std::set<std::string> gIteratorTypes;
1594}
1595
1596static inline
1597bool run_pythonizors(PyObject* pyclass, PyObject* pyname, const std::vector<PyObject*>& v)
1598{
1599 PyObject* args = PyTuple_New(2);
1602
1603 bool pstatus = true;
1604 for (auto pythonizor : v) {
1606 if (!result) {
1607 pstatus = false; // TODO: detail the error handling
1608 break;
1609 }
1611 }
1612 Py_DECREF(args);
1613
1614 return pstatus;
1615}
1616
1617bool CPyCppyy::Pythonize(PyObject* pyclass, const std::string& name)
1618{
1619// Add pre-defined pythonizations (for STL and ROOT) to classes based on their
1620// signature and/or class name.
1621 if (!pyclass)
1622 return false;
1623
1625
1626//- method name based pythonization ------------------------------------------
1627
1628// for smart pointer style classes that are otherwise not known as such; would
1629// prefer operator-> as that returns a pointer (which is simpler since it never
1630// has to deal with ref-assignment), but operator* plays better with STL iters
1631// and algorithms
1636
1637// for pre-check of nullptr for boolean types
1639#if PY_VERSION_HEX >= 0x03000000
1640 const char* pybool_name = "__bool__";
1641#else
1642 const char* pybool_name = "__nonzero__";
1643#endif
1645 }
1646
1647// for STL containers, and user classes modeled after them
1648// the attribute must be a CPyCppyy overload, otherwise the check gives false
1649// positives in the case where the class has a non-function attribute that is
1650// called "size".
1651 if (HasAttrDirect(pyclass, PyStrings::gSize, /*mustBeCPyCppyy=*/ true)) {
1652 Utility::AddToClass(pyclass, "__len__", "size");
1653 }
1654
1655 if (!IsTemplatedSTLClass(name, "vector") && // vector is dealt with below
1658 // obtain the name of the return type
1659 const auto& v = Cppyy::GetMethodIndicesFromName(klass->fCppType, "begin");
1660 if (!v.empty()) {
1661 // check return type; if not explicitly an iterator, add it to the "known" return
1662 // types to add the "next" method on use
1664 const std::string& resname = Cppyy::GetMethodResultType(meth);
1665 bool isIterator = gIteratorTypes.find(resname) != gIteratorTypes.end();
1667 if (resname.find("iterator") == std::string::npos)
1668 gIteratorTypes.insert(resname);
1669 isIterator = true;
1670 }
1671
1672 if (isIterator) {
1673 // install iterator protocol a la STL
1676 } else {
1677 // still okay if this is some pointer type of builtin persuasion (general class
1678 // won't work: the return type needs to understand the iterator protocol)
1679 std::string resolved = Cppyy::ResolveName(resname);
1680 if (resolved.back() == '*' && Cppyy::IsBuiltin(resolved.substr(0, resolved.size()-1))) {
1683 }
1684 }
1685 }
1686 }
1687 if (!((PyTypeObject*)pyclass)->tp_iter && // no iterator resolved
1689 // Python will iterate over __getitem__ using integers, but C++ operator[] will never raise
1690 // a StopIteration. A checked getitem (raising IndexError if beyond size()) works in some
1691 // cases but would mess up if operator[] is meant to implement an associative container. So,
1692 // this has to be implemented as an iterator protocol.
1695 }
1696 }
1697
1698// operator==/!= are used in op_richcompare of CPPInstance, which subsequently allows
1699// comparisons to None; if no operator is available, a hook is installed for lazy
1700// lookups in the global and/or class namespace
1701 if (HasAttrDirect(pyclass, PyStrings::gEq, true) && \
1702 Cppyy::GetMethodIndicesFromName(klass->fCppType, "__eq__").empty()) {
1704 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators();
1705 klass->fOperators->fEq = cppol;
1706 // re-insert the forwarding __eq__ from the CPPInstance in case there was a Python-side
1707 // override in the base class
1708 static PyObject* top_eq = nullptr;
1709 if (!top_eq) {
1712 Py_DECREF(top_eq); // make it borrowed
1714 }
1716 }
1717
1718 if (HasAttrDirect(pyclass, PyStrings::gNe, true) && \
1719 Cppyy::GetMethodIndicesFromName(klass->fCppType, "__ne__").empty()) {
1721 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators();
1722 klass->fOperators->fNe = cppol;
1723 // re-insert the forwarding __ne__ (same reason as above for __eq__)
1724 static PyObject* top_ne = nullptr;
1725 if (!top_ne) {
1728 Py_DECREF(top_ne); // make it borrowed
1730 }
1732 }
1733
1734#if 0
1736 // guarantee that the result of __repr__ is a Python string
1737 Utility::AddToClass(pyclass, "__cpp_repr", "__repr__");
1739 }
1740
1742 // guarantee that the result of __str__ is a Python string
1743 Utility::AddToClass(pyclass, "__cpp_str", "__str__");
1745 }
1746#endif
1747
1748 if (Cppyy::IsAggregate(((CPPClass*)pyclass)->fCppType) && name.compare(0, 5, "std::", 5) != 0 &&
1749 name.compare(0, 6, "tuple<", 6) != 0) {
1750 // create a pseudo-constructor to allow initializer-style object creation
1751 Cppyy::TCppType_t kls = ((CPPClass*)pyclass)->fCppType;
1753 if (ndata) {
1754 std::string rname = name;
1756
1757 std::ostringstream initdef;
1758 initdef << "namespace __cppyy_internal {\n"
1759 << "void init_" << rname << "(" << name << "*& self";
1760 bool codegen_ok = true;
1761 std::vector<std::string> arg_types, arg_names, arg_defaults;
1762 arg_types.reserve(ndata); arg_names.reserve(ndata); arg_defaults.reserve(ndata);
1763 for (Cppyy::TCppIndex_t i = 0; i < ndata; ++i) {
1765 continue;
1766
1767 const std::string& txt = Cppyy::GetDatamemberType(kls, i);
1768 const std::string& res = Cppyy::IsEnum(txt) ? txt : Cppyy::ResolveName(txt);
1769 const std::string& cpd = TypeManip::compound(res);
1770 std::string res_clean = TypeManip::clean_type(res, false, true);
1771
1772 if (res_clean == "internal_enum_type_t")
1773 res_clean = txt; // restore (properly scoped name)
1774
1775 if (res.rfind(']') == std::string::npos && res.rfind(')') == std::string::npos) {
1776 if (!cpd.empty()) arg_types.push_back(res_clean+cpd);
1777 else arg_types.push_back("const "+res_clean+"&");
1778 arg_names.push_back(Cppyy::GetDatamemberName(kls, i));
1779 if ((!cpd.empty() && cpd.back() == '*') || Cppyy::IsBuiltin(res_clean))
1780 arg_defaults.push_back("0");
1781 else {
1784 }
1785 } else {
1786 codegen_ok = false; // TODO: how to support arrays, anonymous enums, etc?
1787 break;
1788 }
1789 }
1790
1791 if (codegen_ok && !arg_types.empty()) {
1792 bool defaults_ok = arg_defaults.size() == arg_types.size();
1793 for (std::vector<std::string>::size_type i = 0; i < arg_types.size(); ++i) {
1794 initdef << ", " << arg_types[i] << " " << arg_names[i];
1795 if (defaults_ok) initdef << " = " << arg_defaults[i];
1796 }
1797 initdef << ") {\n self = new " << name << "{";
1798 for (std::vector<std::string>::size_type i = 0; i < arg_names.size(); ++i) {
1799 if (i != 0) initdef << ", ";
1800 initdef << arg_names[i];
1801 }
1802 initdef << "};\n} }";
1803
1804 if (Cppyy::Compile(initdef.str(), true /* silent */)) {
1805 Cppyy::TCppScope_t cis = Cppyy::GetScope("__cppyy_internal");
1806 const auto& mix = Cppyy::GetMethodIndicesFromName(cis, "init_"+rname);
1807 if (mix.size()) {
1808 if (!Utility::AddToClass(pyclass, "__init__",
1809 new CPPFunction(cis, Cppyy::GetMethod(cis, mix[0]))))
1810 PyErr_Clear();
1811 }
1812 }
1813 }
1814 }
1815 }
1816
1817
1818//- class name based pythonization -------------------------------------------
1819
1820 if (IsTemplatedSTLClass(name, "vector")) {
1821
1822 // std::vector<bool> is a special case in C++
1824 if (klass->fCppType == sVectorBoolTypeID) {
1827 } else {
1828 // constructor that takes python collections
1829 Utility::AddToClass(pyclass, "__real_init", "__init__");
1831
1832 // data with size
1833 Utility::AddToClass(pyclass, "__real_data", "data");
1835
1836 // The addition of the __array__ utility to std::vector Python proxies causes a
1837 // bug where the resulting array is a single dimension, causing loss of data when
1838 // converting to numpy arrays, for >1dim vectors. Since this C++ pythonization
1839 // was added with the upgrade in 6.32, and is only defined and used recursively,
1840 // the safe option is to disable this function and no longer add it.
1841#if 0
1842 // numpy array conversion
1844#endif
1845
1846 // checked getitem
1848 Utility::AddToClass(pyclass, "_getitem__unchecked", "__getitem__");
1850 }
1851
1852 // vector-optimized iterator protocol
1854
1855 // optimized __iadd__
1857
1858 // helpers for iteration
1859 const std::string& vtype = Cppyy::ResolveName(name+"::value_type");
1860 if (vtype.rfind("value_type") == std::string::npos) { // actually resolved?
1864 }
1865
1866 size_t typesz = Cppyy::SizeOf(name+"::value_type");
1867 if (typesz) {
1871 }
1872 }
1873 }
1874
1875 else if (IsTemplatedSTLClass(name, "array")) {
1876 // constructor that takes python associative collections
1877 Utility::AddToClass(pyclass, "__real_init", "__init__");
1879 }
1880
1881 else if (IsTemplatedSTLClass(name, "map") || IsTemplatedSTLClass(name, "unordered_map")) {
1882 // constructor that takes python associative collections
1883 Utility::AddToClass(pyclass, "__real_init", "__init__");
1885
1887 }
1888
1889 else if (IsTemplatedSTLClass(name, "set")) {
1890 // constructor that takes python associative collections
1891 Utility::AddToClass(pyclass, "__real_init", "__init__");
1893
1895 }
1896
1897 else if (IsTemplatedSTLClass(name, "pair")) {
1900 }
1901
1902 if (IsTemplatedSTLClass(name, "shared_ptr") || IsTemplatedSTLClass(name, "unique_ptr")) {
1903 Utility::AddToClass(pyclass, "__real_init", "__init__");
1905 }
1906
1907 else if (!((PyTypeObject*)pyclass)->tp_iter && \
1908 (name.find("iterator") != std::string::npos || gIteratorTypes.find(name) != gIteratorTypes.end())) {
1909 ((PyTypeObject*)pyclass)->tp_iternext = (iternextfunc)STLIterNext;
1913 }
1914
1915 else if (name == "string" || name == "std::string") { // TODO: ask backend as well
1924 Utility::AddToClass(pyclass, "__cpp_find", "find");
1926 Utility::AddToClass(pyclass, "__cpp_rfind", "rfind");
1928 Utility::AddToClass(pyclass, "__cpp_replace", "replace");
1931
1932 // to allow use of std::string in dictionaries and findable with str
1934 }
1935
1936 else if (name == "basic_string_view<char,char_traits<char> >" || name == "std::basic_string_view<char>") {
1937 Utility::AddToClass(pyclass, "__real_init", "__init__");
1945 }
1946
1947 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> >") {
1954 }
1955
1956 else if (name == "complex<double>" || name == "std::complex<double>") {
1957 Utility::AddToClass(pyclass, "__cpp_real", "real");
1959 Utility::AddToClass(pyclass, "__cpp_imag", "imag");
1963 }
1964
1965 else if (IsTemplatedSTLClass(name, "complex")) {
1966 Utility::AddToClass(pyclass, "__cpp_real", "real");
1968 Utility::AddToClass(pyclass, "__cpp_imag", "imag");
1972 }
1973
1974// direct user access; there are two calls here:
1975// - explicit pythonization: won't fall through to the base classes and is preferred if present
1976// - normal pythonization: only called if explicit isn't present, falls through to base classes
1977 bool bUserOk = true; PyObject* res = nullptr;
1981 bUserOk = (bool)res;
1982 } else {
1984 if (func) {
1985 res = PyObject_CallFunctionObjArgs(func, pyclass, pyname, nullptr);
1986 Py_DECREF(func);
1987 bUserOk = (bool)res;
1988 } else
1989 PyErr_Clear();
1990 }
1991 if (!bUserOk) {
1993 return false;
1994 } else {
1995 Py_XDECREF(res);
1996 // pyname handed to args tuple below
1997 }
1998
1999// call registered pythonizors, if any: first run the namespace-specific pythonizors, then
2000// the global ones (the idea is to allow writing a pythonizor that see all classes)
2001 bool pstatus = true;
2003 auto &pyzMap = pythonizations();
2004 if (!outer_scope.empty()) {
2005 auto p = pyzMap.find(outer_scope);
2006 if (p != pyzMap.end()) {
2008 name.substr(outer_scope.size()+2, std::string::npos).c_str());
2011 }
2012 }
2013
2014 if (pstatus) {
2015 auto p = pyzMap.find("");
2016 if (p != pyzMap.end())
2017 pstatus = run_pythonizors(pyclass, pyname, p->second);
2018 }
2019
2021
2022// phew! all done ...
2023 return pstatus;
2024}
#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
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 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)