Logo ROOT   6.18/05
Reference Guide
Pythonize.cxx
Go to the documentation of this file.
1// @(#)root/pyroot:$Id$
2// Author: Wim Lavrijsen, Jul 2004
3
4// Bindings
5#include "PyROOT.h"
6#include "PyStrings.h"
7#include "Pythonize.h"
8#include "ObjectProxy.h"
9#include "MethodProxy.h"
10#include "RootWrapper.h"
11#include "Utility.h"
12#include "PyCallable.h"
13#include "TPyBufferFactory.h"
14#include "TFunctionHolder.h"
15#include "Converters.h"
16#include "TMemoryRegulator.h"
17#include "Utility.h"
18
19// ROOT
20#include "TClass.h"
21#include "TFunction.h"
22#include "TInterpreter.h"
23#include "TMethod.h"
24
25#include "TClonesArray.h"
26#include "TCollection.h"
27#include "TDirectory.h"
28#include "TError.h"
29#include "TFile.h"
30#include "TKey.h"
31#include "TObject.h"
32#include "TObjArray.h"
33#include "TSeqCollection.h"
34
35#include "TTree.h"
36#include "TBranch.h"
37#include "TBranchElement.h"
38#include "TBranchObject.h"
39#include "TLeaf.h"
40#include "TLeafElement.h"
41#include "TLeafObject.h"
42#include "TStreamerElement.h"
43#include "TStreamerInfo.h"
44#include "TInterpreterValue.h"
45
46#include "ROOT/RVec.hxx"
47
48// Standard
49#include <stdexcept>
50#include <string>
51#include <utility>
52#include <sstream>
53
54#include <stdio.h>
55#include <string.h> // only needed for Cling TMinuit workaround
56
57
58// temp (?)
59static inline TClass* OP2TCLASS( PyROOT::ObjectProxy* pyobj ) {
60 return TClass::GetClass( Cppyy::GetFinalName( pyobj->ObjectIsA() ).c_str());
61}
62//-- temp
63
64//- data and local helpers ---------------------------------------------------
65namespace PyROOT {
67}
68
69namespace {
70
71// for convenience
72 using namespace PyROOT;
73
74////////////////////////////////////////////////////////////////////////////////
75/// prevents calls to Py_TYPE(pyclass)->tp_getattr, which is unnecessary for our
76/// purposes here and could tickle problems w/ spurious lookups into ROOT meta
77
78 Bool_t HasAttrDirect( PyObject* pyclass, PyObject* pyname, Bool_t mustBePyROOT = kFALSE ) {
79 PyObject* attr = PyType_Type.tp_getattro( pyclass, pyname );
80 if ( attr != 0 && ( ! mustBePyROOT || MethodProxy_Check( attr ) ) ) {
81 Py_DECREF( attr );
82 return kTRUE;
83 }
84
85 PyErr_Clear();
86 return kFALSE;
87 }
88
89////////////////////////////////////////////////////////////////////////////////
90/// prevents calls to descriptors
91
92 PyObject* PyObject_GetAttrFromDict( PyObject* pyclass, PyObject* pyname ) {
93 PyObject* dict = PyObject_GetAttr( pyclass, PyStrings::gDict );
94 PyObject* attr = PyObject_GetItem( dict, pyname );
95 Py_DECREF( dict );
96 return attr;
97 }
98
99////////////////////////////////////////////////////////////////////////////////
100/// Scan the name of the class and determine whether it is a template instantiation.
101
102 inline Bool_t IsTemplatedSTLClass( const std::string& name, const std::string& klass ) {
103 const int nsize = (int)name.size();
104 const int ksize = (int)klass.size();
105
106 return ( ( ksize < nsize && name.substr(0,ksize) == klass ) ||
107 ( ksize+5 < nsize && name.substr(5,ksize) == klass ) ) &&
108 name.find( "::", name.find( ">" ) ) == std::string::npos;
109 }
110
111// to prevent compiler warnings about const char* -> char*
112 inline PyObject* CallPyObjMethod( PyObject* obj, const char* meth )
113 {
114 // Helper; call method with signature: obj->meth().
115 Py_INCREF( obj );
116 PyObject* result = PyObject_CallMethod( obj, const_cast< char* >( meth ), const_cast< char* >( "" ) );
117 Py_DECREF( obj );
118 return result;
119 }
120
121////////////////////////////////////////////////////////////////////////////////
122/// Helper; call method with signature: obj->meth( arg1 ).
123
124 inline PyObject* CallPyObjMethod( PyObject* obj, const char* meth, PyObject* arg1 )
125 {
126 Py_INCREF( obj );
127 PyObject* result = PyObject_CallMethod(
128 obj, const_cast< char* >( meth ), const_cast< char* >( "O" ), arg1 );
129 Py_DECREF( obj );
130 return result;
131 }
132
133////////////////////////////////////////////////////////////////////////////////
134/// Helper; call method with signature: obj->meth( arg1, arg2 ).
135
136 inline PyObject* CallPyObjMethod(
137 PyObject* obj, const char* meth, PyObject* arg1, PyObject* arg2 )
138 {
139 Py_INCREF( obj );
140 PyObject* result = PyObject_CallMethod(
141 obj, const_cast< char* >( meth ), const_cast< char* >( "OO" ), arg1, arg2 );
142 Py_DECREF( obj );
143 return result;
144 }
145
146////////////////////////////////////////////////////////////////////////////////
147/// Helper; call method with signature: obj->meth( arg1, int ).
148
149 inline PyObject* CallPyObjMethod( PyObject* obj, const char* meth, PyObject* arg1, int arg2 )
150 {
151 Py_INCREF( obj );
152 PyObject* result = PyObject_CallMethod(
153 obj, const_cast< char* >( meth ), const_cast< char* >( "Oi" ), arg1, arg2 );
154 Py_DECREF( obj );
155 return result;
156 }
157
158
159//- helpers --------------------------------------------------------------------
160 PyObject* PyStyleIndex( PyObject* self, PyObject* index )
161 {
162 // Helper; converts python index into straight C index.
163 Py_ssize_t idx = PyInt_AsSsize_t( index );
164 if ( idx == (Py_ssize_t)-1 && PyErr_Occurred() )
165 return 0;
166
167 Py_ssize_t size = PySequence_Size( self );
168 if ( idx >= size || ( idx < 0 && idx < -size ) ) {
169 PyErr_SetString( PyExc_IndexError, "index out of range" );
170 return 0;
171 }
172
173 PyObject* pyindex = 0;
174 if ( idx >= 0 ) {
175 Py_INCREF( index );
176 pyindex = index;
177 } else
178 pyindex = PyLong_FromLong( size + idx );
179
180 return pyindex;
181 }
182
183////////////////////////////////////////////////////////////////////////////////
184/// Helper; call method with signature: meth( pyindex ).
185
186 inline PyObject* CallSelfIndex( ObjectProxy* self, PyObject* idx, const char* meth )
187 {
188 Py_INCREF( (PyObject*)self );
189 PyObject* pyindex = PyStyleIndex( (PyObject*)self, idx );
190 if ( ! pyindex ) {
191 Py_DECREF( (PyObject*)self );
192 return 0;
193 }
194
195 PyObject* result = CallPyObjMethod( (PyObject*)self, meth, pyindex );
196 Py_DECREF( pyindex );
197 Py_DECREF( (PyObject*)self );
198 return result;
199 }
200
201////////////////////////////////////////////////////////////////////////////////
202/// Helper; convert generic python object into a boolean value.
203
204 inline PyObject* BoolNot( PyObject* value )
205 {
206 if ( PyObject_IsTrue( value ) == 1 ) {
207 Py_INCREF( Py_False );
208 Py_DECREF( value );
209 return Py_False;
210 } else {
211 Py_INCREF( Py_True );
212 Py_XDECREF( value );
213 return Py_True;
214 }
215 }
216
217//- "smart pointer" behavior ---------------------------------------------------
218 PyObject* DeRefGetAttr( PyObject* self, PyObject* name )
219 {
220 // Follow operator*() if present (available in python as __deref__), so that
221 // smart pointers behave as expected.
222 if ( ! PyROOT_PyUnicode_Check( name ) )
223 PyErr_SetString( PyExc_TypeError, "getattr(): attribute name must be string" );
224
225 PyObject* pyptr = CallPyObjMethod( self, "__deref__" );
226 if ( ! pyptr )
227 return 0;
228
229 // prevent a potential infinite loop
230 if ( Py_TYPE(pyptr) == Py_TYPE(self) ) {
231 PyObject* val1 = PyObject_Str( self );
232 PyObject* val2 = PyObject_Str( name );
233 PyErr_Format( PyExc_AttributeError, "%s has no attribute \'%s\'",
235 Py_DECREF( val2 );
236 Py_DECREF( val1 );
237
238 Py_DECREF( pyptr );
239 return 0;
240 }
241
242 PyObject* result = PyObject_GetAttr( pyptr, name );
243 Py_DECREF( pyptr );
244 return result;
245 }
246
247////////////////////////////////////////////////////////////////////////////////
248/// Follow operator->() if present (available in python as __follow__), so that
249/// smart pointers behave as expected.
250
251 PyObject* FollowGetAttr( PyObject* self, PyObject* name )
252 {
253 if ( ! PyROOT_PyUnicode_Check( name ) )
254 PyErr_SetString( PyExc_TypeError, "getattr(): attribute name must be string" );
255
256 PyObject* pyptr = CallPyObjMethod( self, "__follow__" );
257 if ( ! pyptr )
258 return 0;
259
260 PyObject* result = PyObject_GetAttr( pyptr, name );
261 Py_DECREF( pyptr );
262 return result;
263 }
264
265//- TObject behavior -----------------------------------------------------------
266 PyObject* TObjectContains( PyObject* self, PyObject* obj )
267 {
268 // Implement python's __contains__ with TObject::FindObject.
269 if ( ! ( ObjectProxy_Check( obj ) || PyROOT_PyUnicode_Check( obj ) ) )
270 return PyInt_FromLong( 0l );
271
272 PyObject* found = CallPyObjMethod( self, "FindObject", obj );
273 PyObject* result = PyInt_FromLong( PyObject_IsTrue( found ) );
274 Py_DECREF( found );
275 return result;
276 }
277
278////////////////////////////////////////////////////////////////////////////////
279/// Implement python's __cmp__ with TObject::Compare.
280
281 PyObject* TObjectCompare( PyObject* self, PyObject* obj )
282 {
283 if ( ! ObjectProxy_Check( obj ) )
284 return PyInt_FromLong( -1l );
285
286 return CallPyObjMethod( self, "Compare", obj );
287 }
288
289////////////////////////////////////////////////////////////////////////////////
290/// Implement python's __eq__ with TObject::IsEqual.
291
292 PyObject* TObjectIsEqual( PyObject* self, PyObject* obj )
293 {
294 if ( ! ObjectProxy_Check( obj ) || ! ((ObjectProxy*)obj)->fObject )
295 return ObjectProxy_Type.tp_richcompare( self, obj, Py_EQ );
296
297 return CallPyObjMethod( self, "IsEqual", obj );
298 }
299
300////////////////////////////////////////////////////////////////////////////////
301/// Implement python's __ne__ in terms of not TObject::IsEqual.
302
303 PyObject* TObjectIsNotEqual( PyObject* self, PyObject* obj )
304 {
305 if ( ! ObjectProxy_Check( obj ) || ! ((ObjectProxy*)obj)->fObject )
306 return ObjectProxy_Type.tp_richcompare( self, obj, Py_NE );
307
308 return BoolNot( CallPyObjMethod( self, "IsEqual", obj ) );
309 }
310
311////////////////////////////////////////////////////////////////////////////////
312/// Contrary to TObjectIsEqual, it can now not be relied upon that the only
313/// non-ObjectProxy obj is None, as any operator==(), taking any object (e.g.
314/// an enum) can be implemented. However, those cases will yield an exception
315/// if presented with None.
316
317 PyObject* GenObjectIsEqual( PyObject* self, PyObject* obj )
318 {
319 PyObject* result = CallPyObjMethod( self, "__cpp_eq__", obj );
320 if ( ! result ) {
321 PyErr_Clear();
322 result = ObjectProxy_Type.tp_richcompare( self, obj, Py_EQ );
323 }
324
325 return result;
326 }
327
328////////////////////////////////////////////////////////////////////////////////
329/// Reverse of GenObjectIsEqual, if operator!= defined.
330
331 PyObject* GenObjectIsNotEqual( PyObject* self, PyObject* obj )
332 {
333 PyObject* result = CallPyObjMethod( self, "__cpp_ne__", obj );
334 if ( ! result ) {
335 PyErr_Clear();
336 result = ObjectProxy_Type.tp_richcompare( self, obj, Py_NE );
337 }
338
339 return result;
340 }
341
342//- TClass behavior ------------------------------------------------------------
343 PyObject* TClassStaticCast( ObjectProxy* self, PyObject* args )
344 {
345 // Implemented somewhat different than TClass::DynamicClass, in that "up" is
346 // chosen automatically based on the relationship between self and arg pyclass.
347 ObjectProxy* pyclass = 0; PyObject* pyobject = 0;
348 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "O!O:StaticCast" ),
349 &ObjectProxy_Type, &pyclass, &pyobject ) )
350 return 0;
351
352 // check the given arguments (dcasts are necessary b/c of could be a TQClass
353 TClass* from = (TClass*)OP2TCLASS(self)->DynamicCast( TClass::Class(), self->GetObject() );
354 TClass* to = (TClass*)OP2TCLASS(self)->DynamicCast( TClass::Class(), pyclass->GetObject() );
355
356 if ( ! from ) {
357 PyErr_SetString( PyExc_TypeError, "unbound method TClass::StaticCast "
358 "must be called with a TClass instance as first argument" );
359 return 0;
360 }
361
362 if ( ! to ) {
363 PyErr_SetString( PyExc_TypeError, "could not convert argument 1 (TClass* expected)" );
364 return 0;
365 }
366
367 // retrieve object address
368 void* address = 0;
369 if ( ObjectProxy_Check( pyobject ) ) address = ((ObjectProxy*)pyobject)->GetObject();
370 else if ( PyInt_Check( pyobject ) || PyLong_Check( pyobject ) ) address = (void*)PyLong_AsLong( pyobject );
371 else Utility::GetBuffer( pyobject, '*', 1, address, kFALSE );
372
373 if ( ! address ) {
374 PyErr_SetString( PyExc_TypeError, "could not convert argument 2 (void* expected)" );
375 return 0;
376 }
377
378 // determine direction of cast
379 int up = -1;
380 if ( from->InheritsFrom( to ) ) up = 1;
381 else if ( to->InheritsFrom( from ) ) {
382 TClass* tmp = to; to = from; from = tmp;
383 up = 0;
384 }
385
386 if ( up == -1 ) {
387 PyErr_Format( PyExc_TypeError, "unable to cast %s to %s", from->GetName(), to->GetName() );
388 return 0;
389 }
390
391 // perform actual cast
392 void* result = from->DynamicCast( to, address, (Bool_t)up );
393
394 // at this point, "result" can't be null (but is still safe if it is)
395 return BindCppObjectNoCast( result, Cppyy::GetScope( to->GetName() ) );
396 }
397
398////////////////////////////////////////////////////////////////////////////////
399/// TClass::DynamicCast returns a void* that the user still has to cast (it
400/// will have the proper offset, though). Fix this by providing the requested
401/// binding if the cast succeeded.
402
403 PyObject* TClassDynamicCast( ObjectProxy* self, PyObject* args )
404 {
405 ObjectProxy* pyclass = 0; PyObject* pyobject = 0;
406 Long_t up = 1;
407 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "O!O|l:DynamicCast" ),
408 &ObjectProxy_Type, &pyclass, &pyobject, &up ) )
409 return 0;
410
411 // perform actual cast
412 PyObject* meth = PyObject_GetAttr( (PyObject*)self, PyStrings::gTClassDynCast );
413 PyObject* ptr = meth ? PyObject_Call( meth, args, 0 ) : 0;
414 Py_XDECREF( meth );
415
416 // simply forward in case of call failure
417 if ( ! ptr )
418 return ptr;
419
420 // retrieve object address
421 void* address = 0;
422 if ( ObjectProxy_Check( pyobject ) ) address = ((ObjectProxy*)pyobject)->GetObject();
423 else if ( PyInt_Check( pyobject ) || PyLong_Check( pyobject ) ) address = (void*)PyLong_AsLong( pyobject );
424 else Utility::GetBuffer( pyobject, '*', 1, address, kFALSE );
425
426 if ( PyErr_Occurred() ) {
427 PyErr_Clear();
428 return ptr;
429 }
430
431 // now use binding to return a usable class
432 TClass* klass = 0;
433 if ( up ) { // up-cast: result is a base
434 klass = (TClass*)OP2TCLASS(pyclass)->DynamicCast( TClass::Class(), pyclass->GetObject() );
435 } else { // down-cast: result is a derived
436 klass = (TClass*)OP2TCLASS(self)->DynamicCast( TClass::Class(), self->GetObject() );
437 }
438
439 PyObject* result = BindCppObjectNoCast( (void*)address, Cppyy::GetScope( klass->GetName() ) );
440 Py_DECREF( ptr );
441
442 return result;
443 }
444
445//- TCollection behavior -------------------------------------------------------
446 PyObject* TCollectionExtend( PyObject* self, PyObject* obj )
447 {
448 // Implement a python-style extend with TCollection::Add.
449 for ( Py_ssize_t i = 0; i < PySequence_Size( obj ); ++i ) {
450 PyObject* item = PySequence_GetItem( obj, i );
451 PyObject* result = CallPyObjMethod( self, "Add", item );
452 Py_XDECREF( result );
453 Py_DECREF( item );
454 }
455
456 Py_INCREF( Py_None );
457 return Py_None;
458 }
459
460////////////////////////////////////////////////////////////////////////////////
461/// Implement a python-style remove with TCollection::Add.
462
463 PyObject* TCollectionRemove( PyObject* self, PyObject* obj )
464 {
465 PyObject* result = CallPyObjMethod( self, "Remove", obj );
466 if ( ! result )
467 return 0;
468
469 if ( ! PyObject_IsTrue( result ) ) {
470 Py_DECREF( result );
471 PyErr_SetString( PyExc_ValueError, "list.remove(x): x not in list" );
472 return 0;
473 }
474
475 Py_DECREF( result );
476 Py_INCREF( Py_None );
477 return Py_None;
478 }
479
480////////////////////////////////////////////////////////////////////////////////
481/// Implement python's __add__ with the pythonized extend for TCollections.
482
483 PyObject* TCollectionAdd( PyObject* self, PyObject* other )
484 {
485 PyObject* l = CallPyObjMethod( self, "Clone" );
486 if ( ! l )
487 return 0;
488
489 PyObject* result = CallPyObjMethod( l, "extend", other );
490 if ( ! result ) {
491 Py_DECREF( l );
492 return 0;
493 }
494
495 return l;
496 }
497
498////////////////////////////////////////////////////////////////////////////////
499/// Implement python's __mul__ with the pythonized extend for TCollections.
500
501 PyObject* TCollectionMul( ObjectProxy* self, PyObject* pymul )
502 {
503 Long_t imul = PyLong_AsLong( pymul );
504 if ( imul == -1 && PyErr_Occurred() )
505 return 0;
506
507 if ( ! self->GetObject() ) {
508 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
509 return 0;
510 }
511
512 PyObject* nseq = BindCppObject(
513 Cppyy::Construct( self->ObjectIsA() ), self->ObjectIsA() );
514
515 for ( Long_t i = 0; i < imul; ++i ) {
516 PyObject* result = CallPyObjMethod( nseq, "extend", (PyObject*)self );
517 Py_DECREF( result );
518 }
519
520 return nseq;
521 }
522
523////////////////////////////////////////////////////////////////////////////////
524/// Implement python's __imul__ with the pythonized extend for TCollections.
525
526 PyObject* TCollectionIMul( PyObject* self, PyObject* pymul )
527 {
528 Long_t imul = PyLong_AsLong( pymul );
529 if ( imul == -1 && PyErr_Occurred() )
530 return 0;
531
532 PyObject* l = PySequence_List( self );
533
534 for ( Long_t i = 0; i < imul - 1; ++i ) {
535 CallPyObjMethod( self, "extend", l );
536 }
537
538 Py_INCREF( self );
539 return self;
540 }
541
542////////////////////////////////////////////////////////////////////////////////
543/// Implement a python-style count for TCollections.
544
545 PyObject* TCollectionCount( PyObject* self, PyObject* obj )
546 {
547 Py_ssize_t count = 0;
548 for ( Py_ssize_t i = 0; i < PySequence_Size( self ); ++i ) {
549 PyObject* item = PySequence_GetItem( self, i );
550 PyObject* found = PyObject_RichCompare( item, obj, Py_EQ );
551
552 Py_DECREF( item );
553
554 if ( ! found )
555 return 0; // internal problem
556
557 if ( PyObject_IsTrue( found ) )
558 count += 1;
559 Py_DECREF( found );
560 }
561
562 return PyInt_FromSsize_t( count );
563 }
564
565////////////////////////////////////////////////////////////////////////////////
566/// Python __iter__ protocol for TCollections.
567
568 PyObject* TCollectionIter( ObjectProxy* self ) {
569 if ( ! self->GetObject() ) {
570 PyErr_SetString( PyExc_TypeError, "iteration over non-sequence" );
571 return 0;
572 }
573
574 TCollection* col =
576
577 PyObject* pyobject = BindCppObject( (void*) new TIter( col ), "TIter" );
578 ((ObjectProxy*)pyobject)->HoldOn();
579 return pyobject;
580 }
581
582
583//- TSeqCollection behavior ----------------------------------------------------
584 PyObject* TSeqCollectionGetItem( ObjectProxy* self, PySliceObject* index )
585 {
586 // Python-style indexing and size checking for getting objects from a TCollection.
587 if ( PySlice_Check( index ) ) {
588 if ( ! self->GetObject() ) {
589 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
590 return 0;
591 }
592
593 TClass* clSeq = OP2TCLASS(self);
594 TSeqCollection* oseq =
596 TSeqCollection* nseq = (TSeqCollection*)clSeq->New();
597
598 Py_ssize_t start, stop, step;
599 PySlice_GetIndices( (PyROOT_PySliceCast)index, oseq->GetSize(), &start, &stop, &step );
600
601 for ( Py_ssize_t i = start; i < stop; i += step ) {
602 nseq->Add( oseq->At( (Int_t)i ) );
603 }
604
605 return BindCppObject( (void*) nseq, clSeq->GetName() );
606 }
607
608 return CallSelfIndex( self, (PyObject*)index, "At" );
609 }
610
611////////////////////////////////////////////////////////////////////////////////
612/// Python-style indexing and size checking for setting objects in a TCollection.
613
614 PyObject* TSeqCollectionSetItem( ObjectProxy* self, PyObject* args )
615 {
616 PyObject* index = 0, *obj = 0;
617 if ( ! PyArg_ParseTuple( args,
618 const_cast< char* >( "OO:__setitem__" ), &index, &obj ) )
619 return 0;
620
621 if ( PySlice_Check( index ) ) {
622 if ( ! self->GetObject() ) {
623 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
624 return 0;
625 }
626
628 TSeqCollection::Class(), self->GetObject() );
629
630 Py_ssize_t start, stop, step;
631 PySlice_GetIndices( (PyROOT_PySliceCast)index, oseq->GetSize(), &start, &stop, &step );
632 for ( Py_ssize_t i = stop - step; i >= start; i -= step ) {
633 oseq->RemoveAt( (Int_t)i );
634 }
635
636 for ( Py_ssize_t i = 0; i < PySequence_Size( obj ); ++i ) {
637 ObjectProxy* item = (ObjectProxy*)PySequence_GetItem( obj, i );
638 item->Release();
639 oseq->AddAt( (TObject*) item->GetObject(), (Int_t)(i + start) );
640 Py_DECREF( item );
641 }
642
643 Py_INCREF( Py_None );
644 return Py_None;
645 }
646
647 PyObject* pyindex = PyStyleIndex( (PyObject*)self, index );
648 if ( ! pyindex )
649 return 0;
650
651 PyObject* result = CallPyObjMethod( (PyObject*)self, "RemoveAt", pyindex );
652 if ( ! result ) {
653 Py_DECREF( pyindex );
654 return 0;
655 }
656
657 Py_DECREF( result );
658 result = CallPyObjMethod( (PyObject*)self, "AddAt", obj, pyindex );
659 Py_DECREF( pyindex );
660 return result;
661 }
662
663////////////////////////////////////////////////////////////////////////////////
664/// Implement python's __del__ with TCollection::RemoveAt.
665
666 PyObject* TSeqCollectionDelItem( ObjectProxy* self, PySliceObject* index )
667 {
668 if ( PySlice_Check( index ) ) {
669 if ( ! self->GetObject() ) {
670 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
671 return 0;
672 }
673
675 TSeqCollection::Class(), self->GetObject() );
676
677 Py_ssize_t start, stop, step;
678 PySlice_GetIndices( (PyROOT_PySliceCast)index, oseq->GetSize(), &start, &stop, &step );
679 for ( Py_ssize_t i = stop - step; i >= start; i -= step ) {
680 oseq->RemoveAt( (Int_t)i );
681 }
682
683 Py_INCREF( Py_None );
684 return Py_None;
685 }
686
687 PyObject* result = CallSelfIndex( self, (PyObject*)index, "RemoveAt" );
688 if ( ! result )
689 return 0;
690
691 Py_DECREF( result );
692 Py_INCREF( Py_None );
693 return Py_None;
694 }
695
696////////////////////////////////////////////////////////////////////////////////
697/// Python-style insertion implemented with TCollection::AddAt.
698
699 PyObject* TSeqCollectionInsert( PyObject* self, PyObject* args )
700 {
701 PyObject* obj = 0; Long_t idx = 0;
702 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "lO:insert" ), &idx, &obj ) )
703 return 0;
704
705 Py_ssize_t size = PySequence_Size( self );
706 if ( idx < 0 )
707 idx = 0;
708 else if ( size < idx )
709 idx = size;
710
711 return CallPyObjMethod( self, "AddAt", obj, idx );
712 }
713
714////////////////////////////////////////////////////////////////////////////////
715/// Implement a python-style pop for TCollections.
716
717 PyObject* TSeqCollectionPop( ObjectProxy* self, PyObject* args )
718 {
719 int nArgs = PyTuple_GET_SIZE( args );
720 if ( nArgs == 0 ) {
721 // create the default argument 'end of sequence'
722 PyObject* index = PyInt_FromSsize_t( PySequence_Size( (PyObject*)self ) - 1 );
723 PyObject* result = CallSelfIndex( self, index, "RemoveAt" );
724 Py_DECREF( index );
725 return result;
726 } else if ( nArgs != 1 ) {
727 PyErr_Format( PyExc_TypeError,
728 "pop() takes at most 1 argument (%d given)", nArgs );
729 return 0;
730 }
731
732 return CallSelfIndex( self, PyTuple_GET_ITEM( args, 0 ), "RemoveAt" );
733 }
734
735////////////////////////////////////////////////////////////////////////////////
736/// Implement a python-style reverse for TCollections.
737
738 PyObject* TSeqCollectionReverse( PyObject* self )
739 {
740 PyObject* tup = PySequence_Tuple( self );
741 if ( ! tup )
742 return 0;
743
744 PyObject* result = CallPyObjMethod( self, "Clear" );
745 Py_XDECREF( result );
746
747 for ( Py_ssize_t i = 0; i < PySequence_Size( tup ); ++i ) {
748 PyObject* retval = CallPyObjMethod( self, "AddAt", PyTuple_GET_ITEM( tup, i ), 0 );
749 Py_XDECREF( retval );
750 }
751
752 Py_INCREF( Py_None );
753 return Py_None;
754 }
755
756////////////////////////////////////////////////////////////////////////////////
757/// Implement a python-style sort for TCollections.
758
759 PyObject* TSeqCollectionSort( PyObject* self, PyObject* args, PyObject* kw )
760 {
761 if ( PyTuple_GET_SIZE( args ) == 0 && ! kw ) {
762 // no specialized sort, use ROOT one
763 return CallPyObjMethod( self, "Sort" );
764 } else {
765 // sort in a python list copy
766 PyObject* l = PySequence_List( self );
767 PyObject* result = 0;
768 if ( PyTuple_GET_SIZE( args ) == 1 )
769 result = CallPyObjMethod( l, "sort", PyTuple_GET_ITEM( args, 0 ) );
770 else {
771 PyObject* pymeth = PyObject_GetAttrString( l, const_cast< char* >( "sort" ) );
772 result = PyObject_Call( pymeth, args, kw );
773 Py_DECREF( pymeth );
774 }
775
776 Py_XDECREF( result );
777 if ( PyErr_Occurred() ) {
778 Py_DECREF( l );
779 return 0;
780 }
781
782 result = CallPyObjMethod( self, "Clear" );
783 Py_XDECREF( result );
784 result = CallPyObjMethod( self, "extend", l );
785 Py_XDECREF( result );
786 Py_DECREF( l );
787
788 Py_INCREF( Py_None );
789 return Py_None;
790 }
791 }
792
793////////////////////////////////////////////////////////////////////////////////
794/// Implement a python-style index with TCollection::IndexOf.
795
796 PyObject* TSeqCollectionIndex( PyObject* self, PyObject* obj )
797 {
798 PyObject* index = CallPyObjMethod( self, "IndexOf", obj );
799 if ( ! index )
800 return 0;
801
802 if ( PyLong_AsLong( index ) < 0 ) {
803 Py_DECREF( index );
804 PyErr_SetString( PyExc_ValueError, "list.index(x): x not in list" );
805 return 0;
806 }
807
808 return index;
809 }
810
811//- TObjArray behavior ---------------------------------------------------------
812 PyObject* TObjArrayLen( PyObject* self )
813 {
814 // GetSize on a TObjArray returns its capacity, not size in use
815 PyObject* size = CallPyObjMethod( self, "GetLast" );
816 if ( ! size )
817 return 0;
818
819 long lsize = PyLong_AsLong( size );
820 if ( lsize == -1 && PyErr_Occurred() )
821 return 0;
822
823 Py_DECREF( size );
824 return PyInt_FromLong( lsize + 1 );
825 }
826
827
828//- TClonesArray behavior ------------------------------------------------------
829 PyObject* TClonesArraySetItem( ObjectProxy* self, PyObject* args )
830 {
831 // TClonesArray sets objects by constructing them in-place; which is impossible
832 // to support as the python object given as value must exist a priori. It can,
833 // however, be memcpy'd and stolen, caveat emptor.
834 ObjectProxy* pyobj = 0; PyObject* idx = 0;
835 if ( ! PyArg_ParseTuple( args,
836 const_cast< char* >( "OO!:__setitem__" ), &idx, &ObjectProxy_Type, &pyobj ) )
837 return 0;
838
839 if ( ! self->GetObject() ) {
840 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
841 return 0;
842 }
843
844 PyObject* pyindex = PyStyleIndex( (PyObject*)self, idx );
845 if ( ! pyindex )
846 return 0;
847 int index = (int)PyLong_AsLong( pyindex );
848 Py_DECREF( pyindex );
849
850 // get hold of the actual TClonesArray
851 TClonesArray* cla =
853
854 if ( ! cla ) {
855 PyErr_SetString( PyExc_TypeError, "attempt to call with null object" );
856 return 0;
857 }
858
859 if ( Cppyy::GetScope( cla->GetClass()->GetName() ) != pyobj->ObjectIsA() ) {
860 PyErr_Format( PyExc_TypeError, "require object of type %s, but %s given",
861 cla->GetClass()->GetName(), Cppyy::GetFinalName( pyobj->ObjectIsA() ).c_str() );
862 }
863
864 // destroy old stuff, if applicable
865 if ( ((const TClonesArray&)*cla)[index] ) {
866 cla->RemoveAt( index );
867 }
868
869 if ( pyobj->GetObject() ) {
870 // accessing an entry will result in new, unitialized memory (if properly used)
871 TObject* object = (*cla)[index];
872 pyobj->Release();
873 TMemoryRegulator::RegisterObject( pyobj, object );
874 memcpy( (void*)object, pyobj->GetObject(), cla->GetClass()->Size() );
875 }
876
877 Py_INCREF( Py_None );
878 return Py_None;
879 }
880
881//- vector behavior as primitives ----------------------------------------------
882 typedef struct {
883 PyObject_HEAD
884 PyObject* vi_vector;
885 void* vi_data;
886 PyROOT::TConverter* vi_converter;
887 Py_ssize_t vi_pos;
888 Py_ssize_t vi_len;
889 Py_ssize_t vi_stride;
890 } vectoriterobject;
891
892 static void vectoriter_dealloc( vectoriterobject* vi ) {
893 Py_XDECREF( vi->vi_vector );
894 delete vi->vi_converter;
895 PyObject_GC_Del( vi );
896 }
897
898 static int vectoriter_traverse( vectoriterobject* vi, visitproc visit, void* arg ) {
899 Py_VISIT( vi->vi_vector );
900 return 0;
901 }
902
903 static PyObject* vectoriter_iternext( vectoriterobject* vi ) {
904 if ( vi->vi_pos >= vi->vi_len )
905 return nullptr;
906
907 PyObject* result = nullptr;
908
909 if ( vi->vi_data && vi->vi_converter ) {
910 void* location = (void*)((ptrdiff_t)vi->vi_data + vi->vi_stride * vi->vi_pos );
911 result = vi->vi_converter->FromMemory( location );
912 } else {
913 PyObject* pyindex = PyLong_FromLong( vi->vi_pos );
914 result = CallPyObjMethod( (PyObject*)vi->vi_vector, "_vector__at", pyindex );
915 Py_DECREF( pyindex );
916 }
917
918 vi->vi_pos += 1;
919 return result;
920 }
921
922#if !defined(_MSC_VER)
923#pragma GCC diagnostic push
924#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
925#endif
926
927 PyTypeObject VectorIter_Type = {
928 PyVarObject_HEAD_INIT( &PyType_Type, 0 )
929 (char*)"ROOT.vectoriter", // tp_name
930 sizeof(vectoriterobject), // tp_basicsize
931 0,
932 (destructor)vectoriter_dealloc, // tp_dealloc
933 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
934 Py_TPFLAGS_DEFAULT |
935 Py_TPFLAGS_HAVE_GC, // tp_flags
936 0,
937 (traverseproc)vectoriter_traverse, // tp_traverse
938 0, 0, 0,
939 PyObject_SelfIter, // tp_iter
940 (iternextfunc)vectoriter_iternext, // tp_iternext
941 0, // tp_methods
942 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
943#if PY_VERSION_HEX >= 0x02030000
944 , 0 // tp_del
945#endif
946#if PY_VERSION_HEX >= 0x02060000
947 , 0 // tp_version_tag
948#endif
949#if PY_VERSION_HEX >= 0x03040000
950 , 0 // tp_finalize
951#endif
952#if PY_VERSION_HEX >= 0x03080000
953 , 0 // tp_vectorcall
954#if PY_VERSION_HEX < 0x03090000
955 , 0 // tp_print (python 3.8 only)
956#endif
957#endif
958 };
959
960#if !defined(_MSC_VER)
961#pragma GCC diagnostic pop
962#endif
963
964 static PyObject* vector_iter( PyObject* v ) {
965 vectoriterobject* vi = PyObject_GC_New( vectoriterobject, &VectorIter_Type );
966 if ( ! vi ) return NULL;
967
968 Py_INCREF( v );
969 vi->vi_vector = v;
970
971 PyObject* pyvalue_type = PyObject_GetAttrString( (PyObject*)Py_TYPE(v), "value_type" );
972 PyObject* pyvalue_size = PyObject_GetAttrString( (PyObject*)Py_TYPE(v), "value_size" );
973
974 if ( pyvalue_type && pyvalue_size ) {
975 PyObject* pydata = CallPyObjMethod( v, "data" );
976 if ( !pydata || Utility::GetBuffer( pydata, '*', 1, vi->vi_data, kFALSE ) == 0 )
977 vi->vi_data = nullptr;
978 Py_XDECREF( pydata );
979
980 vi->vi_converter = PyROOT::CreateConverter( PyROOT_PyUnicode_AsString( pyvalue_type ) );
981 vi->vi_stride = PyLong_AsLong( pyvalue_size );
982 } else {
983 PyErr_Clear();
984 vi->vi_data = nullptr;
985 vi->vi_converter = nullptr;
986 vi->vi_stride = 0;
987 }
988
989 Py_XDECREF( pyvalue_size );
990 Py_XDECREF( pyvalue_type );
991
992 vi->vi_len = vi->vi_pos = 0;
993 vi->vi_len = PySequence_Size( v );
994
995 PyObject_GC_Track( vi );
996 return (PyObject*)vi;
997 }
998
999
1000 PyObject* VectorGetItem( ObjectProxy* self, PySliceObject* index )
1001 {
1002 // Implement python's __getitem__ for std::vector<>s.
1003 if ( PySlice_Check( index ) ) {
1004 if ( ! self->GetObject() ) {
1005 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
1006 return 0;
1007 }
1008
1009 PyObject* pyclass = PyObject_GetAttr( (PyObject*)self, PyStrings::gClass );
1010 PyObject* nseq = PyObject_CallObject( pyclass, NULL );
1011 Py_DECREF( pyclass );
1012
1013 Py_ssize_t start, stop, step;
1014 PySlice_GetIndices( (PyROOT_PySliceCast)index, PyObject_Length( (PyObject*)self ), &start, &stop, &step );
1015 for ( Py_ssize_t i = start; i < stop; i += step ) {
1016 PyObject* pyidx = PyInt_FromSsize_t( i );
1017 CallPyObjMethod( nseq, "push_back", CallPyObjMethod( (PyObject*)self, "_vector__at", pyidx ) );
1018 Py_DECREF( pyidx );
1019 }
1020
1021 return nseq;
1022 }
1023
1024 return CallSelfIndex( self, (PyObject*)index, "_vector__at" );
1025 }
1026
1027 PyObject* VectorBoolSetItem( ObjectProxy* self, PyObject* args )
1028 {
1029 // std::vector<bool> is a special-case in C++, and its return type depends on
1030 // the compiler: treat it special here as well
1031 int bval = 0; PyObject* idx = 0;
1032 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "Oi:__setitem__" ), &idx, &bval ) )
1033 return 0;
1034
1035 if ( ! self->GetObject() ) {
1036 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
1037 return 0;
1038 }
1039
1040 PyObject* pyindex = PyStyleIndex( (PyObject*)self, idx );
1041 if ( ! pyindex )
1042 return 0;
1043 int index = (int)PyLong_AsLong( pyindex );
1044 Py_DECREF( pyindex );
1045
1046 std::string clName = Cppyy::GetFinalName( self->ObjectIsA() );
1047 std::string::size_type pos = clName.find( "vector<bool" );
1048 if ( pos != 0 && pos != 5 /* following std:: */ ) {
1049 PyErr_Format( PyExc_TypeError,
1050 "require object of type std::vector<bool>, but %s given",
1051 Cppyy::GetFinalName( self->ObjectIsA() ).c_str() );
1052 return 0;
1053 }
1054
1055 // get hold of the actual std::vector<bool> (no cast, as vector is never a base)
1056 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
1057
1058 // finally, set the value
1059 (*vb)[ index ] = (bool)bval;
1060
1061 Py_INCREF( Py_None );
1062 return Py_None;
1063 }
1064
1065//- map behavior as primitives ------------------------------------------------
1066 PyObject* MapContains( PyObject* self, PyObject* obj )
1067 {
1068 // Implement python's __contains__ for std::map<>s.
1069 PyObject* result = 0;
1070
1071 PyObject* iter = CallPyObjMethod( self, "find", obj );
1072 if ( ObjectProxy_Check( iter ) ) {
1073 PyObject* end = CallPyObjMethod( self, "end" );
1074 if ( ObjectProxy_Check( end ) ) {
1075 if ( ! PyObject_RichCompareBool( iter, end, Py_EQ ) ) {
1076 Py_INCREF( Py_True );
1077 result = Py_True;
1078 }
1079 }
1080 Py_XDECREF( end );
1081 }
1082 Py_XDECREF( iter );
1083
1084 if ( ! result ) {
1085 PyErr_Clear(); // e.g. wrong argument type, which should always lead to False
1086 Py_INCREF( Py_False );
1087 result = Py_False;
1088 }
1089
1090 return result;
1091 }
1092
1093//- STL container iterator support --------------------------------------------
1094 PyObject* StlSequenceIter( PyObject* self )
1095 {
1096 // Implement python's __iter__ for std::iterator<>s.
1097 PyObject* iter = CallPyObjMethod( self, "begin" );
1098 if ( iter ) {
1099 PyObject* end = CallPyObjMethod( self, "end" );
1100 if ( end )
1101 PyObject_SetAttr( iter, PyStrings::gEnd, end );
1102 Py_XDECREF( end );
1103
1104 // add iterated collection as attribute so its refcount stays >= 1 while it's being iterated over
1105 PyObject_SetAttr( iter, PyUnicode_FromString("_collection"), self );
1106 }
1107 return iter;
1108 }
1109
1110//- safe indexing for STL-like vector w/o iterator dictionaries ---------------
1111 PyObject* CheckedGetItem( PyObject* self, PyObject* obj )
1112 {
1113 // Implement a generic python __getitem__ for std::vector<>s that are missing
1114 // their std::vector<>::iterator dictionary. This is then used for iteration
1115 // by means of consecutive index.
1116 Bool_t inbounds = kFALSE;
1117 Py_ssize_t size = PySequence_Size( self );
1118 Py_ssize_t idx = PyInt_AsSsize_t( obj );
1119 if ( 0 <= idx && 0 <= size && idx < size )
1120 inbounds = kTRUE;
1121
1122 if ( inbounds ) {
1123 return CallPyObjMethod( self, "_getitem__unchecked", obj );
1124 } else if ( PyErr_Occurred() ) {
1125 // argument conversion problem: let method itself resolve anew and report
1126 PyErr_Clear();
1127 return CallPyObjMethod( self, "_getitem__unchecked", obj );
1128 } else {
1129 PyErr_SetString( PyExc_IndexError, "index out of range" );
1130 }
1131
1132 return 0;
1133 }
1134
1135//- pair as sequence to allow tuple unpacking ---------------------------------
1136 PyObject* PairUnpack( PyObject* self, PyObject* pyindex )
1137 {
1138 // For std::map<> iteration, unpack std::pair<>s into tuples for the loop.
1139 Long_t idx = PyLong_AsLong( pyindex );
1140 if ( idx == -1 && PyErr_Occurred() )
1141 return 0;
1142
1143 if ( ! ObjectProxy_Check( self ) || ! ((ObjectProxy*)self)->GetObject() ) {
1144 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
1145 return 0;
1146 }
1147
1148 if ( (int)idx == 0 )
1149 return PyObject_GetAttr( self, PyStrings::gFirst );
1150 else if ( (int)idx == 1 )
1151 return PyObject_GetAttr( self, PyStrings::gSecond );
1152
1153 // still here? Trigger stop iteration
1154 PyErr_SetString( PyExc_IndexError, "out of bounds" );
1155 return 0;
1156 }
1157
1158//- string behavior as primitives ----------------------------------------------
1159#if PY_VERSION_HEX >= 0x03000000
1160// TODO: this is wrong, b/c it doesn't order
1161static int PyObject_Compare( PyObject* one, PyObject* other ) {
1162 return ! PyObject_RichCompareBool( one, other, Py_EQ );
1163}
1164#endif
1165 static inline PyObject* PyROOT_PyString_FromCppString( std::string* s ) {
1166 return PyROOT_PyUnicode_FromStringAndSize( s->c_str(), s->size() );
1167 }
1168
1169 static inline PyObject* PyROOT_PyString_FromCppString( TString* s ) {
1170 return PyROOT_PyUnicode_FromStringAndSize( s->Data(), s->Length() );
1171 }
1172
1173 static inline PyObject* PyROOT_PyString_FromCppString( TObjString* s ) {
1174 return PyROOT_PyUnicode_FromStringAndSize( s->GetString().Data(), s->GetString().Length() );
1175 }
1176
1177#define PYROOT_IMPLEMENT_STRING_PYTHONIZATION( type, name ) \
1178 inline PyObject* name##GetData( PyObject* self ) { \
1179 if ( PyROOT::ObjectProxy_Check( self ) ) { \
1180 type* obj = ((type*)((ObjectProxy*)self)->GetObject()); \
1181 if ( obj ) { \
1182 return PyROOT_PyString_FromCppString( obj ); \
1183 } else { \
1184 return ObjectProxy_Type.tp_str( self ); \
1185 } \
1186 } \
1187 PyErr_Format( PyExc_TypeError, "object mismatch (%s expected)", #type );\
1188 return 0; \
1189 } \
1190 \
1191 PyObject* name##StringRepr( PyObject* self ) \
1192 { \
1193 PyObject* data = name##GetData( self ); \
1194 if ( data ) { \
1195 PyObject* repr = PyROOT_PyUnicode_FromFormat( "\'%s\'", PyROOT_PyUnicode_AsString( data ) ); \
1196 Py_DECREF( data ); \
1197 return repr; \
1198 } \
1199 return 0; \
1200 } \
1201 \
1202 PyObject* name##StringIsEqual( PyObject* self, PyObject* obj ) \
1203 { \
1204 PyObject* data = name##GetData( self ); \
1205 if ( data ) { \
1206 PyObject* result = PyObject_RichCompare( data, obj, Py_EQ ); \
1207 Py_DECREF( data ); \
1208 return result; \
1209 } \
1210 return 0; \
1211 } \
1212 \
1213 PyObject* name##StringIsNotEqual( PyObject* self, PyObject* obj ) \
1214 { \
1215 PyObject* data = name##GetData( self ); \
1216 if ( data ) { \
1217 PyObject* result = PyObject_RichCompare( data, obj, Py_NE ); \
1218 Py_DECREF( data ); \
1219 return result; \
1220 } \
1221 return 0; \
1222 }
1223
1224 // Only define StlStringCompare:
1225 // TStringCompare is unused and generates a warning;
1226#define PYROOT_IMPLEMENT_STRING_PYTHONIZATION_CMP( type, name ) \
1227 PYROOT_IMPLEMENT_STRING_PYTHONIZATION( type, name ) \
1228 PyObject* name##StringCompare( PyObject* self, PyObject* obj ) \
1229 { \
1230 PyObject* data = name##GetData( self ); \
1231 int result = 0; \
1232 if ( data ) { \
1233 result = PyObject_Compare( data, obj ); \
1234 Py_DECREF( data ); \
1235 } \
1236 if ( PyErr_Occurred() ) \
1237 return 0; \
1238 return PyInt_FromLong( result ); \
1239 }
1240
1243
1244
1245//- TObjString behavior --------------------------------------------------------
1247
1248////////////////////////////////////////////////////////////////////////////////
1249/// Implementation of python __len__ for TObjString.
1250
1251 PyObject* TObjStringLength( PyObject* self )
1252 {
1253 PyObject* data = CallPyObjMethod( self, "GetName" );
1254 Py_ssize_t size = PySequence_Size( data );
1255 Py_DECREF( data );
1256 return PyInt_FromSsize_t( size );
1257 }
1258
1259
1260//- TIter behavior -------------------------------------------------------------
1261 PyObject* TIterNext( PyObject* self )
1262 {
1263 // Implementation of python __next__ (iterator protocol) for TIter.
1264 PyObject* next = CallPyObjMethod( self, "Next" );
1265
1266 if ( ! next )
1267 return 0;
1268
1269 if ( ! PyObject_IsTrue( next ) ) {
1270 Py_DECREF( next );
1271 PyErr_SetString( PyExc_StopIteration, "" );
1272 return 0;
1273 }
1274
1275 return next;
1276 }
1277
1278
1279//- STL iterator behavior ------------------------------------------------------
1280 PyObject* StlIterNext( PyObject* self )
1281 {
1282 // Python iterator protocol __next__ for STL forward iterators.
1283 PyObject* next = 0;
1284 PyObject* last = PyObject_GetAttr( self, PyStrings::gEnd );
1285
1286 if ( last != 0 ) {
1287 // handle special case of empty container (i.e. self is end)
1288 if ( PyObject_RichCompareBool( last, self, Py_EQ ) ) {
1289 PyErr_SetString( PyExc_StopIteration, "" );
1290 } else {
1291 PyObject* dummy = PyInt_FromLong( 1l );
1292 PyObject* iter = CallPyObjMethod( self, "__postinc__", dummy );
1293 Py_DECREF( dummy );
1294 if ( iter != 0 ) {
1295 if ( PyObject_RichCompareBool( last, iter, Py_EQ ) )
1296 PyErr_SetString( PyExc_StopIteration, "" );
1297 else
1298 next = CallPyObjMethod( iter, "__deref__" );
1299 } else {
1300 PyErr_SetString( PyExc_StopIteration, "" );
1301 }
1302 Py_XDECREF( iter );
1303 }
1304 } else {
1305 PyErr_SetString( PyExc_StopIteration, "" );
1306 }
1307
1308 Py_XDECREF( last );
1309 return next;
1310 }
1311
1312////////////////////////////////////////////////////////////////////////////////
1313/// Called if operator== not available (e.g. if a global overload as under gcc).
1314/// An exception is raised as the user should fix the dictionary.
1315
1316 PyObject* StlIterIsEqual( PyObject* self, PyObject* other )
1317 {
1318 return PyErr_Format( PyExc_LookupError,
1319 "No operator==(const %s&, const %s&) available in the dictionary!",
1320 Utility::ClassName( self ).c_str(), Utility::ClassName( other ).c_str() );
1321 }
1322
1323////////////////////////////////////////////////////////////////////////////////
1324/// Called if operator!= not available (e.g. if a global overload as under gcc).
1325/// An exception is raised as the user should fix the dictionary.
1326
1327 PyObject* StlIterIsNotEqual( PyObject* self, PyObject* other )
1328 {
1329 return PyErr_Format( PyExc_LookupError,
1330 "No operator!=(const %s&, const %s&) available in the dictionary!",
1331 Utility::ClassName( self ).c_str(), Utility::ClassName( other ).c_str() );
1332 }
1333
1334
1335//- TDirectory member templates ----------------------------------------------
1336 PyObject* TDirectoryGetObject( ObjectProxy* self, PyObject* args )
1337 {
1338 // Pythonization of TDirector::GetObject().
1339 PyObject* name = 0; ObjectProxy* ptr = 0;
1340 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "O!O!:TDirectory::GetObject" ),
1342 return 0;
1343
1344 TDirectory* dir =
1346
1347 if ( ! dir ) {
1348 PyErr_SetString( PyExc_TypeError,
1349 "TDirectory::GetObject must be called with a TDirectory instance as first argument" );
1350 return 0;
1351 }
1352
1353 void* address = dir->GetObjectChecked( PyROOT_PyUnicode_AsString( name ), OP2TCLASS(ptr) );
1354 if ( address ) {
1355 ptr->Set( address );
1356
1357 Py_INCREF( Py_None );
1358 return Py_None;
1359 }
1360
1361 PyErr_Format( PyExc_LookupError, "no such object, \"%s\"", PyROOT_PyUnicode_AsString( name ) );
1362 return 0;
1363 }
1364
1365////////////////////////////////////////////////////////////////////////////////
1366/// Type-safe version of TDirectory::WriteObjectAny, which is a template for
1367/// the same reason on the C++ side.
1368
1369 PyObject* TDirectoryWriteObject( ObjectProxy* self, PyObject* args )
1370 {
1371 ObjectProxy *wrt = 0; PyObject *name = 0, *option = 0;
1372 Int_t bufsize = 0;
1373 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "O!O!|O!i:TDirectory::WriteObject" ),
1375 &PyROOT_PyUnicode_Type, &option, &bufsize ) )
1376 return 0;
1377
1378 TDirectory* dir =
1380
1381 if ( ! dir ) {
1382 PyErr_SetString( PyExc_TypeError,
1383 "TDirectory::WriteObject must be called with a TDirectory instance as first argument" );
1384 return 0;
1385 }
1386
1387 Int_t result = 0;
1388 if ( option != 0 ) {
1389 result = dir->WriteObjectAny( wrt->GetObject(), OP2TCLASS(wrt),
1391 } else {
1392 result = dir->WriteObjectAny(
1394 }
1395
1396 return PyInt_FromLong( (Long_t)result );
1397 }
1398
1399}
1400
1401
1402namespace PyROOT { // workaround for Intel icc on Linux
1403
1404//- TTree behavior ------------------------------------------------------------
1406 {
1407 // allow access to branches/leaves as if they are data members
1408 const char* name1 = PyROOT_PyUnicode_AsString( pyname );
1409 if ( ! name1 )
1410 return 0;
1411
1412 // get hold of actual tree
1413 TTree* tree =
1414 (TTree*)OP2TCLASS(self)->DynamicCast( TTree::Class(), self->GetObject() );
1415
1416 if ( ! tree ) {
1417 PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
1418 return 0;
1419 }
1420
1421 // deal with possible aliasing
1422 const char* name = tree->GetAlias( name1 );
1423 if ( ! name ) name = name1;
1424
1425 // search for branch first (typical for objects)
1426 TBranch* branch = tree->GetBranch( name );
1427 if ( ! branch ) {
1428 // for benefit of naming of sub-branches, the actual name may have a trailing '.'
1429 branch = tree->GetBranch( (std::string( name ) + '.' ).c_str() );
1430 }
1431
1432 if ( branch ) {
1433 // found a branched object, wrap its address for the object it represents
1434
1435 // for partial return of a split object
1436 if ( branch->InheritsFrom(TBranchElement::Class()) ) {
1437 TBranchElement* be = (TBranchElement*)branch;
1438 if ( be->GetCurrentClass() && (be->GetCurrentClass() != be->GetTargetClass()) && (0 <= be->GetID()) ) {
1439 Long_t offset = ((TStreamerElement*)be->GetInfo()->GetElements()->At(be->GetID()))->GetOffset();
1440 return BindCppObjectNoCast( be->GetObject() + offset, Cppyy::GetScope( be->GetCurrentClass()->GetName() ) );
1441 }
1442 }
1443
1444 // for return of a full object
1445 if ( branch->IsA() == TBranchElement::Class() || branch->IsA() == TBranchObject::Class() ) {
1446 TClass* klass = TClass::GetClass( branch->GetClassName() );
1447 if ( klass && branch->GetAddress() )
1448 return BindCppObjectNoCast( *(void**)branch->GetAddress(), Cppyy::GetScope( branch->GetClassName() ) );
1449
1450 // try leaf, otherwise indicate failure by returning a typed null-object
1451 TObjArray* leaves = branch->GetListOfLeaves();
1452 if ( klass && ! tree->GetLeaf( name ) &&
1453 ! (leaves->GetSize() && ( leaves->First() == leaves->Last() ) ) )
1454 return BindCppObjectNoCast( NULL, Cppyy::GetScope( branch->GetClassName() ) );
1455 }
1456 }
1457
1458 // if not, try leaf
1459 TLeaf* leaf = tree->GetLeaf( name );
1460 if ( branch && ! leaf ) {
1461 leaf = branch->GetLeaf( name );
1462 if ( ! leaf ) {
1463 TObjArray* leaves = branch->GetListOfLeaves();
1464 if ( leaves->GetSize() && ( leaves->First() == leaves->Last() ) ) {
1465 // i.e., if unambiguously only this one
1466 leaf = (TLeaf*)leaves->At( 0 );
1467 }
1468 }
1469 }
1470
1471 if ( leaf ) {
1472 // found a leaf, extract value and wrap
1473 if ( 1 < leaf->GetLenStatic() || leaf->GetLeafCount() ) {
1474 // array types
1475 std::string typeName = leaf->GetTypeName();
1476 TConverter* pcnv = CreateConverter( typeName + '*', leaf->GetNdata() );
1477
1478 void* address = 0;
1479 if ( leaf->GetBranch() ) address = (void*)leaf->GetBranch()->GetAddress();
1480 if ( ! address ) address = (void*)leaf->GetValuePointer();
1481
1482 PyObject* value = pcnv->FromMemory( &address );
1483 delete pcnv;
1484
1485 return value;
1486 } else if ( leaf->GetValuePointer() ) {
1487 // value types
1488 TConverter* pcnv = CreateConverter( leaf->GetTypeName() );
1489 PyObject* value = 0;
1490 if ( leaf->IsA() == TLeafElement::Class() || leaf->IsA() == TLeafObject::Class() )
1491 value = pcnv->FromMemory( (void*)*(void**)leaf->GetValuePointer() );
1492 else
1493 value = pcnv->FromMemory( (void*)leaf->GetValuePointer() );
1494 delete pcnv;
1495
1496 return value;
1497 }
1498 }
1499
1500 // confused
1501 PyErr_Format( PyExc_AttributeError,
1502 "\'%s\' object has no attribute \'%s\'", tree->IsA()->GetName(), name );
1503 return 0;
1504 }
1505
1506////////////////////////////////////////////////////////////////////////////////
1507
1508 class TTreeMemberFunction : public PyCallable {
1509 protected:
1510 TTreeMemberFunction( MethodProxy* org ) { Py_INCREF( org ); fOrg = org; }
1511 TTreeMemberFunction( const TTreeMemberFunction& t ) : PyCallable( t )
1512 {
1513 // Copy constructor; conform to python reference counting.
1514 Py_INCREF( t.fOrg );
1515 fOrg = t.fOrg;
1516 }
1517 TTreeMemberFunction& operator=( const TTreeMemberFunction& t )
1518 {
1519 // Assignment operator; conform to python reference counting.
1520 if ( &t != this ) {
1521 Py_INCREF( t.fOrg );
1522 Py_XDECREF( fOrg );
1523 fOrg = t.fOrg;
1524 }
1525 return *this;
1526 }
1527 ~TTreeMemberFunction() { Py_DECREF( fOrg ); fOrg = 0; }
1528
1529 public:
1530 virtual PyObject* GetSignature() { return PyROOT_PyUnicode_FromString( "(...)" ); }
1531 virtual PyObject* GetPrototype() { return PyObject_GetAttrString( (PyObject*)fOrg, (char*)"__doc__" ); }
1532 virtual Int_t GetPriority() { return 100; }
1533 virtual PyObject* GetCoVarNames() {
1534 PyObject* co_varnames = PyTuple_New( 1 /* self */ + 1 /* fake */ );
1535 PyTuple_SET_ITEM( co_varnames, 0, PyROOT_PyUnicode_FromString( "self" ) );
1536 PyTuple_SET_ITEM( co_varnames, 1, PyROOT_PyUnicode_FromString( "*args" ) );
1537 return co_varnames;
1538 }
1539 virtual PyObject* GetArgDefault( Int_t ) { return NULL; }
1540 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TTree" ); }
1541
1542 protected:
1543 MethodProxy* fOrg;
1544 };
1545
1546////////////////////////////////////////////////////////////////////////////////
1547
1548 class TTreeBranch : public TTreeMemberFunction {
1549 public:
1550 TTreeBranch( MethodProxy* org ) : TTreeMemberFunction( org ) {}
1551
1552 public:
1553 virtual Int_t GetMaxArgs() { return 5; }
1554 virtual PyCallable* Clone() { return new TTreeBranch( *this ); }
1555
1556 virtual PyObject* Call(
1557 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* /* ctxt */ )
1558 {
1559 // acceptable signatures:
1560 // ( const char*, void*, const char*, Int_t = 32000 )
1561 // ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
1562 // ( const char*, T**, Int_t = 32000, Int_t = 99 )
1563 int argc = PyTuple_GET_SIZE( args );
1564
1565 if ( 2 <= argc ) {
1566 TTree* tree =
1567 (TTree*)OP2TCLASS(self)->DynamicCast( TTree::Class(), self->GetObject() );
1568
1569 if ( ! tree ) {
1570 PyErr_SetString( PyExc_TypeError,
1571 "TTree::Branch must be called with a TTree instance as first argument" );
1572 return 0;
1573 }
1574
1575 PyObject *name = 0, *clName = 0, *leaflist = 0;
1576 PyObject *address = 0;
1577 PyObject *bufsize = 0, *splitlevel = 0;
1578
1579 // try: ( const char*, void*, const char*, Int_t = 32000 )
1580 if ( PyArg_ParseTuple( args, const_cast< char* >( "O!OO!|O!:Branch" ),
1582 &leaflist, &PyInt_Type, &bufsize ) ) {
1583
1584 void* buf = 0;
1585 if ( ObjectProxy_Check( address ) )
1586 buf = (void*)((ObjectProxy*)address)->GetObject();
1587 else
1588 Utility::GetBuffer( address, '*', 1, buf, kFALSE );
1589
1590 if ( buf != 0 ) {
1591 TBranch* branch = 0;
1592 if ( argc == 4 ) {
1593 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), buf,
1594 PyROOT_PyUnicode_AsString( leaflist ), PyInt_AS_LONG( bufsize ) );
1595 } else {
1596 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), buf,
1597 PyROOT_PyUnicode_AsString( leaflist ) );
1598 }
1599
1600 return BindCppObject( branch, "TBranch" );
1601 }
1602
1603 }
1604 PyErr_Clear();
1605
1606 // try: ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
1607 // or: ( const char*, T**, Int_t = 32000, Int_t = 99 )
1608 Bool_t bIsMatch = kFALSE;
1609 if ( PyArg_ParseTuple( args, const_cast< char* >( "O!O!O|O!O!:Branch" ),
1610 &PyROOT_PyUnicode_Type, &name, &PyROOT_PyUnicode_Type, &clName, &address,
1611 &PyInt_Type, &bufsize, &PyInt_Type, &splitlevel ) ) {
1612 bIsMatch = kTRUE;
1613 } else {
1614 PyErr_Clear(); clName = 0; // clName no longer used
1615 if ( PyArg_ParseTuple( args, const_cast< char* >( "O!O|O!O!" ),
1616 &PyROOT_PyUnicode_Type, &name, &address,
1617 &PyInt_Type, &bufsize, &PyInt_Type, &splitlevel ) ) {
1618 bIsMatch = kTRUE;
1619 } else
1620 PyErr_Clear();
1621 }
1622
1623 if ( bIsMatch == kTRUE ) {
1624 std::string klName = clName ? PyROOT_PyUnicode_AsString( clName ) : "";
1625 void* buf = 0;
1626
1627 if ( ObjectProxy_Check( address ) ) {
1628 if ( ((ObjectProxy*)address)->fFlags & ObjectProxy::kIsReference )
1629 buf = (void*)((ObjectProxy*)address)->fObject;
1630 else
1631 buf = (void*)&((ObjectProxy*)address)->fObject;
1632
1633 if ( ! clName ) {
1634 klName = OP2TCLASS((ObjectProxy*)address)->GetName();
1635 argc += 1;
1636 }
1637 } else
1638 Utility::GetBuffer( address, '*', 1, buf, kFALSE );
1639
1640 if ( buf != 0 && klName != "" ) {
1641 TBranch* branch = 0;
1642 if ( argc == 3 ) {
1643 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), klName.c_str(), buf );
1644 } else if ( argc == 4 ) {
1645 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), klName.c_str(), buf,
1646 PyInt_AS_LONG( bufsize ) );
1647 } else if ( argc == 5 ) {
1648 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), klName.c_str(), buf,
1649 PyInt_AS_LONG( bufsize ), PyInt_AS_LONG( splitlevel ) );
1650 }
1651
1652 return BindCppObject( branch, "TBranch" );
1653 }
1654 }
1655 }
1656
1657 // still here? Then call original Branch() to reach the other overloads:
1658 Py_INCREF( (PyObject*)self );
1659 fOrg->fSelf = self;
1660 PyObject* result = PyObject_Call( (PyObject*)fOrg, args, kwds );
1661 fOrg->fSelf = 0;
1662 Py_DECREF( (PyObject*)self );
1663
1664 return result;
1665 }
1666 };
1667
1668////////////////////////////////////////////////////////////////////////////////
1669
1670 class TTreeSetBranchAddress : public TTreeMemberFunction {
1671 public:
1672 TTreeSetBranchAddress( MethodProxy* org ) : TTreeMemberFunction( org ) {}
1673
1674 public:
1675 virtual PyObject* GetPrototype()
1676 {
1677 return PyROOT_PyUnicode_FromString( "TBranch* TTree::SetBranchAddress( ... )" );
1678 }
1679
1680 virtual Int_t GetMaxArgs() { return 2; }
1681 virtual PyCallable* Clone() { return new TTreeSetBranchAddress( *this ); }
1682
1683 virtual PyObject* Call(
1684 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* /* ctxt */ )
1685 {
1686 // acceptable signature:
1687 // ( const char*, void* )
1688 int argc = PyTuple_GET_SIZE( args );
1689
1690 if ( 2 == argc ) {
1691 TTree* tree =
1692 (TTree*)OP2TCLASS(self)->DynamicCast( TTree::Class(), self->GetObject() );
1693
1694 if ( ! tree ) {
1695 PyErr_SetString( PyExc_TypeError,
1696 "TTree::SetBranchAddress must be called with a TTree instance as first argument" );
1697 return 0;
1698 }
1699
1700 PyObject *name = 0, *address = 0;
1701
1702 // try: ( const char*, void* )
1703 if ( PyArg_ParseTuple( args, const_cast< char* >( "SO:SetBranchAddress" ),
1704 &name, &address ) ) {
1705
1706 void* buf = 0;
1707 if ( ObjectProxy_Check( address ) ) {
1708 if ( ((ObjectProxy*)address)->fFlags & ObjectProxy::kIsReference )
1709 buf = (void*)((ObjectProxy*)address)->fObject;
1710 else
1711 buf = (void*)&((ObjectProxy*)address)->fObject;
1712 } else
1713 Utility::GetBuffer( address, '*', 1, buf, kFALSE );
1714
1715 if ( buf != 0 ) {
1716 tree->SetBranchAddress( PyROOT_PyUnicode_AsString( name ), buf );
1717
1718 Py_INCREF( Py_None );
1719 return Py_None;
1720 }
1721 }
1722 }
1723
1724 // still here? Then call original Branch() to reach the other overloads:
1725 Py_INCREF( (PyObject*)self );
1726 fOrg->fSelf = self;
1727 PyObject* result = PyObject_Call( (PyObject*)fOrg, args, kwds );
1728 fOrg->fSelf = 0;
1729 Py_DECREF( (PyObject*)self );
1730
1731 return result;
1732 }
1733
1734 protected:
1735 virtual PyObject* ReportTypeError()
1736 {
1737 PyErr_SetString( PyExc_TypeError,
1738 "TTree::SetBranchAddress must be called with a TTree instance as first argument" );
1739 return 0;
1740 }
1741 };
1742
1743
1744// TChain overrides TTree's SetBranchAddress, so set it again (the python method only forwards
1745// onto a TTree*, so the C++ virtual function call will make sure the right method is used)
1746 class TChainSetBranchAddress : public TTreeSetBranchAddress {
1747 public:
1748 TChainSetBranchAddress( MethodProxy* org ) : TTreeSetBranchAddress( org ) {}
1749
1750 public:
1751 virtual PyObject* GetPrototype()
1752 {
1753 return PyROOT_PyUnicode_FromString( "TBranch* TChain::SetBranchAddress( ... )" );
1754 }
1755
1756 virtual Int_t GetMaxArgs() { return 2; }
1757 virtual PyCallable* Clone() { return new TChainSetBranchAddress( *this ); }
1758
1759 protected:
1760 virtual PyObject* ReportTypeError()
1761 {
1762 PyErr_SetString( PyExc_TypeError,
1763 "TChain::SetBranchAddress must be called with a TChain instance as first argument" );
1764 return 0;
1765 }
1766 };
1767
1768//- TMinuit behavior ----------------------------------------------------------
1769 void TMinuitPyCallback( void* vpyfunc, Long_t /* npar */,
1770 Int_t& a0, Double_t* a1, Double_t& a2, Double_t* a3, Int_t a4 ) {
1771 // a void* was passed to keep the interface on builtin types only
1772 PyObject* pyfunc = (PyObject*)vpyfunc;
1773
1774 // prepare arguments
1775 PyObject* pya0 = BufFac_t::Instance()->PyBuffer_FromMemory( &a0, sizeof(Int_t) );
1776 PyObject* pya1 = BufFac_t::Instance()->PyBuffer_FromMemory( a1, a0 * sizeof(Double_t) );
1777 PyObject* pya2 = BufFac_t::Instance()->PyBuffer_FromMemory( &a2, sizeof(Double_t) );
1778 PyObject* pya3 = BufFac_t::Instance()->PyBuffer_FromMemory( a3, -1 ); // size unknown
1779
1780 if ( ! (pya0 && pya1 && pya2 && pya3) ) {
1781 Py_XDECREF( pya3 ); Py_XDECREF( pya2 ); Py_XDECREF( pya1 ); Py_XDECREF( pya0 );
1782 return;
1783 }
1784
1785 // perform actual call
1786 PyObject* result = PyObject_CallFunction(
1787 pyfunc, (char*)"OOOOi", pya0, pya1, pya2, pya3, a4 );
1788 Py_DECREF( pya3 ); Py_DECREF( pya2 ); Py_DECREF( pya1 ); Py_DECREF( pya0 );
1789
1790 if ( ! result ) {
1791 PyErr_Print();
1792 throw std::runtime_error( "TMinuit python fit function call failed" );
1793 }
1794
1795 Py_XDECREF( result );
1796 }
1797
1798//- TFN behavior --------------------------------------------------------------
1799 double TFNPyCallback( void* vpyfunc, Long_t npar, double* a0, double* a1 ) {
1800 // a void* was passed to keep the interface on builtin types only
1801 PyObject* pyfunc = (PyObject*)vpyfunc;
1802
1803 // prepare arguments and call
1804 PyObject* pya0 = BufFac_t::Instance()->PyBuffer_FromMemory( a0, 4 * sizeof(double) );
1805 if ( ! pya0 )
1806 return 0.;
1807
1808 PyObject* result = 0;
1809 if ( npar != 0 ) {
1810 PyObject* pya1 = BufFac_t::Instance()->PyBuffer_FromMemory( a1, npar * sizeof(double) );
1811 result = PyObject_CallFunction( pyfunc, (char*)"OO", pya0, pya1 );
1812 Py_DECREF( pya1 );
1813 } else
1814 result = PyObject_CallFunction( pyfunc, (char*)"O", pya0 );
1815
1816 Py_DECREF( pya0 );
1817
1818 // translate result, throw if an error has occurred
1819 double d = 0.;
1820 if ( ! result ) {
1821 PyErr_Print();
1822 throw std::runtime_error( "TFN python function call failed" );
1823 } else {
1824 d = PyFloat_AsDouble( result );
1825 Py_DECREF( result );
1826 }
1827
1828 return d;
1829 }
1830
1831} // namespace PyROOT
1832
1833
1834namespace {
1835
1836// for convenience
1837 using namespace PyROOT;
1838
1839//- THN behavior --------------------------------------------------------------
1840 PyObject* THNIMul( PyObject* self, PyObject* scale )
1841 {
1842 // Use THN::Scale to perform *= ... need this stub to return self.
1843 PyObject* result = CallPyObjMethod( self, "Scale", scale );
1844 if ( ! result )
1845 return result;
1846
1847 Py_DECREF( result );
1848 Py_INCREF( self );
1849 return self;
1850 }
1851
1852
1853////////////////////////////////////////////////////////////////////////////////
1854
1855 class TPretendInterpreted: public PyCallable {
1856 public:
1857 TPretendInterpreted( int nArgs ) : fNArgs( nArgs ) {}
1858
1859 public:
1860 Int_t GetNArgs() { return fNArgs; }
1861 virtual Int_t GetPriority() { return 100; }
1862 virtual Int_t GetMaxArgs() { return GetNArgs()+1; }
1863 virtual PyObject* GetCoVarNames() {
1864 PyObject* co_varnames = PyTuple_New( 1 /* self */ + 1 /* fake */ );
1865 PyTuple_SET_ITEM( co_varnames, 0, PyROOT_PyUnicode_FromString( "self" ) );
1866 PyTuple_SET_ITEM( co_varnames, 1, PyROOT_PyUnicode_FromString( "*args" ) );
1867 return co_varnames;
1868 }
1869 virtual PyObject* GetArgDefault( Int_t ) { return NULL; }
1870
1871 Bool_t IsCallable( PyObject* pyobject )
1872 {
1873 // Determine whether the given pyobject is indeed callable.
1874 if ( ! pyobject || ! PyCallable_Check( pyobject ) ) {
1875 PyObject* str = pyobject ? PyObject_Str( pyobject ) : PyROOT_PyUnicode_FromString( "null pointer" );
1876 PyErr_Format( PyExc_ValueError,
1877 "\"%s\" is not a valid python callable", PyROOT_PyUnicode_AsString( str ) );
1878 Py_DECREF( str );
1879 return kFALSE;
1880 }
1881
1882 return kTRUE;
1883 }
1884
1885 private:
1886 Int_t fNArgs;
1887 };
1888
1889////////////////////////////////////////////////////////////////////////////////
1890
1891 class TF1InitWithPyFunc : public TPretendInterpreted {
1892 public:
1893 TF1InitWithPyFunc( int ntf = 1 ) : TPretendInterpreted( 2 + 2*ntf ) {}
1894
1895 public:
1896 virtual PyObject* GetSignature() { return PyROOT_PyUnicode_FromString( "(...)" ); }
1897 virtual PyObject* GetPrototype()
1898 {
1900 "TF1::TF1(const char* name, PyObject* callable, "
1901 "Double_t xmin, Double_t xmax, Int_t npar = 0)" );
1902 }
1903 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TF1" ); }
1904 virtual PyCallable* Clone() { return new TF1InitWithPyFunc( *this ); }
1905
1906 virtual PyObject* Call(
1907 ObjectProxy*& self, PyObject* args, PyObject* /* kwds */, TCallContext* /* ctxt */ )
1908 {
1909 // expected signature: ( char* name, pyfunc, double xmin, double xmax, int npar = 0 )
1910 int argc = PyTuple_GET_SIZE( args );
1911 const int reqNArgs = GetNArgs();
1912 if ( ! ( argc == reqNArgs || argc == reqNArgs+1 ) ) {
1913 PyErr_Format( PyExc_TypeError,
1914 "TFN::TFN(const char*, PyObject* callable, ...) =>\n"
1915 " takes at least %d and at most %d arguments (%d given)",
1916 reqNArgs, reqNArgs+1, argc );
1917 return 0; // reported as an overload failure
1918 }
1919
1920 PyObject* pyfunc = PyTuple_GET_ITEM( args, 1 );
1921
1922 // verify/setup the callback parameters
1923 Long_t npar = 0; // default value if not given
1924 if ( argc == reqNArgs+1 )
1925 npar = PyInt_AsLong( PyTuple_GET_ITEM( args, reqNArgs ) );
1926
1927 // create signature
1928 std::vector<std::string> signature; signature.reserve( 2 );
1929 signature.push_back( "double*" );
1930 signature.push_back( "double*" );
1931
1932 // registration with Cling
1933 void* fptr = Utility::CreateWrapperMethod(
1934 pyfunc, npar, "double", signature, "TFNPyCallback" );
1935 if ( ! fptr /* PyErr was set */ )
1936 return 0;
1937
1938 // get constructor
1939 MethodProxy* method =
1940 (MethodProxy*)PyObject_GetAttr( (PyObject*)self, PyStrings::gInit );
1941
1942 // build new argument array
1943 PyObject* newArgs = PyTuple_New( reqNArgs + 1 );
1944
1945 for ( int iarg = 0; iarg < argc; ++iarg ) {
1946 PyObject* item = PyTuple_GET_ITEM( args, iarg );
1947 if ( iarg != 1 ) {
1948 Py_INCREF( item );
1949 PyTuple_SET_ITEM( newArgs, iarg, item );
1950 } else {
1951 PyTuple_SET_ITEM( newArgs, iarg, PyROOT_PyCapsule_New( fptr, NULL, NULL ) );
1952 }
1953 }
1954
1955 if ( argc == reqNArgs ) // meaning: use default for last value
1956 PyTuple_SET_ITEM( newArgs, reqNArgs, PyInt_FromLong( 0l ) );
1957
1958 // re-run constructor, will select the proper one with void* for callback
1959 PyObject* result = PyObject_CallObject( (PyObject*)method, newArgs );
1960
1961 // done, may have worked, if not: 0 is returned
1962 Py_DECREF( newArgs );
1963 Py_DECREF( method );
1964 return result;
1965 }
1966 };
1967
1968////////////////////////////////////////////////////////////////////////////////
1969
1970 class TF2InitWithPyFunc : public TF1InitWithPyFunc {
1971 public:
1972 TF2InitWithPyFunc() : TF1InitWithPyFunc( 2 ) {}
1973
1974 public:
1975 virtual PyObject* GetPrototype()
1976 {
1978 "TF2::TF2(const char* name, PyObject* callable, "
1979 "Double_t xmin, Double_t xmax, "
1980 "Double_t ymin, Double_t ymax, Int_t npar = 0)" );
1981 }
1982 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TF2" ); }
1983 virtual PyCallable* Clone() { return new TF2InitWithPyFunc( *this ); }
1984 };
1985
1986////////////////////////////////////////////////////////////////////////////////
1987
1988 class TF3InitWithPyFunc : public TF1InitWithPyFunc {
1989 public:
1990 TF3InitWithPyFunc() : TF1InitWithPyFunc( 3 ) {}
1991
1992 public:
1993 virtual PyObject* GetPrototype()
1994 {
1996 "TF3::TF3(const char* name, PyObject* callable, "
1997 "Double_t xmin, Double_t xmax, "
1998 "Double_t ymin, Double_t ymax, "
1999 "Double_t zmin, Double_t zmax, Int_t npar = 0)" );
2000 }
2001 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TF3" ); }
2002 virtual PyCallable* Clone() { return new TF3InitWithPyFunc( *this ); }
2003 };
2004
2005//- TFunction behavior ---------------------------------------------------------
2006 PyObject* TFunctionCall( ObjectProxy*& self, PyObject* args ) {
2007 return TFunctionHolder( Cppyy::gGlobalScope, (Cppyy::TCppMethod_t)self->GetObject() ).Call( self, args, 0 );
2008 }
2009
2010
2011//- TMinuit behavior -----------------------------------------------------------
2012 class TMinuitSetFCN : public TPretendInterpreted {
2013 public:
2014 TMinuitSetFCN( int nArgs = 1 ) : TPretendInterpreted( nArgs ) {}
2015
2016 public:
2017 virtual PyObject* GetSignature() { return PyROOT_PyUnicode_FromString( "(PyObject* callable)" ); }
2018 virtual PyObject* GetPrototype()
2019 {
2021 "TMinuit::SetFCN(PyObject* callable)" );
2022 }
2023 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TMinuit" ); }
2024 virtual PyCallable* Clone() { return new TMinuitSetFCN( *this ); }
2025
2026 virtual PyObject* Call(
2027 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* ctxt )
2028 {
2029 // expected signature: ( pyfunc )
2030 int argc = PyTuple_GET_SIZE( args );
2031 if ( argc != 1 ) {
2032 PyErr_Format( PyExc_TypeError,
2033 "TMinuit::SetFCN(PyObject* callable, ...) =>\n"
2034 " takes exactly 1 argument (%d given)", argc );
2035 return 0; // reported as an overload failure
2036 }
2037
2038 PyObject* pyfunc = PyTuple_GET_ITEM( args, 0 );
2039 if ( ! IsCallable( pyfunc ) )
2040 return 0;
2041
2042 // create signature
2043 std::vector<std::string> signature; signature.reserve( 5 );
2044 signature.push_back( "Int_t&" );
2045 signature.push_back( "Double_t*" );
2046 signature.push_back( "Double_t&" );
2047 signature.push_back( "Double_t*" );
2048 signature.push_back( "Int_t" );
2049
2050 // registration with Cling
2051 void* fptr = Utility::CreateWrapperMethod(
2052 pyfunc, 5, "void", signature, "TMinuitPyCallback" );
2053 if ( ! fptr /* PyErr was set */ )
2054 return 0;
2055
2056 // get setter function
2057 MethodProxy* method =
2058 (MethodProxy*)PyObject_GetAttr( (PyObject*)self, PyStrings::gSetFCN );
2059
2060 // CLING WORKAROUND: SetFCN(void* fun) is deprecated but for whatever reason
2061 // still available yet not functional; select the correct one based on its
2062 // signature of the full function pointer
2063 PyCallable* setFCN = 0;
2064 const MethodProxy::Methods_t& methods = method->fMethodInfo->fMethods;
2065 for ( MethodProxy::Methods_t::const_iterator im = methods.begin(); im != methods.end(); ++im ) {
2066 PyObject* sig = (*im)->GetSignature();
2067 if ( sig && strstr( PyROOT_PyUnicode_AsString( sig ), "Double_t&" ) ) {
2068 // the comparison was not exact, but this is just a workaround
2069 setFCN = *im;
2070 Py_DECREF( sig );
2071 break;
2072 }
2073 Py_DECREF( sig );
2074 }
2075 if ( ! setFCN ) // this never happens but Coverity insists; it can be
2076 return 0; // removed with the workaround in due time
2077 // END CLING WORKAROUND
2078
2079 // build new argument array
2080 PyObject* newArgs = PyTuple_New( 1 );
2081 PyTuple_SET_ITEM( newArgs, 0, PyROOT_PyCapsule_New( fptr, NULL, NULL ) );
2082
2083 // re-run
2084 // CLING WORKAROUND: this is to be the call once TMinuit is fixed:
2085 // PyObject* result = PyObject_CallObject( (PyObject*)method, newArgs );
2086 PyObject* result = setFCN->Call( self, newArgs, kwds, ctxt );
2087 // END CLING WORKAROUND
2088
2089 // done, may have worked, if not: 0 is returned
2090 Py_DECREF( newArgs );
2091 Py_DECREF( method );
2092 return result;
2093 }
2094 };
2095
2096 class TMinuitFitterSetFCN : public TMinuitSetFCN {
2097 public:
2098 TMinuitFitterSetFCN() : TMinuitSetFCN( 1 ) {}
2099
2100 public:
2101 virtual PyObject* GetPrototype()
2102 {
2104 "TMinuitFitter::SetFCN(PyObject* callable)" );
2105 }
2106
2107 virtual PyCallable* Clone() { return new TMinuitFitterSetFCN( *this ); }
2108
2109 virtual PyObject* Call(
2110 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* ctxt )
2111 {
2112 // expected signature: ( pyfunc )
2113 int argc = PyTuple_GET_SIZE( args );
2114 if ( argc != 1 ) {
2115 PyErr_Format( PyExc_TypeError,
2116 "TMinuitFitter::SetFCN(PyObject* callable, ...) =>\n"
2117 " takes exactly 1 argument (%d given)", argc );
2118 return 0; // reported as an overload failure
2119 }
2120
2121 return TMinuitSetFCN::Call( self, args, kwds, ctxt );
2122 }
2123 };
2124
2125//- Fit::TFitter behavior ------------------------------------------------------
2126 PyObject* gFitterPyCallback = 0;
2127
2128 void FitterPyCallback( int& npar, double* gin, double& f, double* u, int flag )
2129 {
2130 // Cling-callable callback for Fit::Fitter derived objects.
2131 PyObject* result = 0;
2132
2133 // prepare arguments
2134 PyObject* arg1 = BufFac_t::Instance()->PyBuffer_FromMemory( &npar );
2135
2136 PyObject* arg2 = BufFac_t::Instance()->PyBuffer_FromMemory( gin );
2137
2138 PyObject* arg3 = PyList_New( 1 );
2139 PyList_SetItem( arg3, 0, PyFloat_FromDouble( f ) );
2140
2141 PyObject* arg4 = BufFac_t::Instance()->PyBuffer_FromMemory( u, npar * sizeof(double) );
2142
2143 // perform actual call
2144 result = PyObject_CallFunction(
2145 gFitterPyCallback, (char*)"OOOOi", arg1, arg2, arg3, arg4, flag );
2146 f = PyFloat_AsDouble( PyList_GetItem( arg3, 0 ) );
2147
2148 Py_DECREF( arg4 ); Py_DECREF( arg3 ); Py_DECREF( arg2 ); Py_DECREF( arg1 );
2149
2150 if ( ! result ) {
2151 PyErr_Print();
2152 throw std::runtime_error( "TMinuit python fit function call failed" );
2153 }
2154
2155 Py_XDECREF( result );
2156 }
2157
2158 class TFitterFitFCN : public TPretendInterpreted {
2159 public:
2160 TFitterFitFCN() : TPretendInterpreted( 2 ) {}
2161
2162 public:
2163 virtual PyObject* GetSignature()
2164 {
2166 "(PyObject* callable, int npar = 0, const double* params = 0, unsigned int dataSize = 0, bool chi2fit = false)" );
2167 }
2168 virtual PyObject* GetPrototype()
2169 {
2171 "TFitter::FitFCN(PyObject* callable, int npar = 0, const double* params = 0, unsigned int dataSize = 0, bool chi2fit = false)" );
2172 }
2173 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TFitter" ); }
2174 virtual PyCallable* Clone() { return new TFitterFitFCN( *this ); }
2175
2176 virtual PyObject* Call(
2177 ObjectProxy*& self, PyObject* args, PyObject* /* kwds */, TCallContext* /* ctxt */ )
2178 {
2179 // expected signature: ( self, pyfunc, int npar = 0, const double* params = 0, unsigned int dataSize = 0, bool chi2fit = false )
2180 int argc = PyTuple_GET_SIZE( args );
2181 if ( argc < 1 ) {
2182 PyErr_Format( PyExc_TypeError,
2183 "TFitter::FitFCN(PyObject* callable, ...) =>\n"
2184 " takes at least 1 argument (%d given)", argc );
2185 return 0; // reported as an overload failure
2186 }
2187
2188 PyObject* pyfunc = PyTuple_GET_ITEM( args, 0 );
2189 if ( ! IsCallable( pyfunc ) )
2190 return 0;
2191
2192 // global registration
2193 Py_XDECREF( gFitterPyCallback );
2194 Py_INCREF( pyfunc );
2195 gFitterPyCallback = pyfunc;
2196
2197 // get function
2198 MethodProxy* method =
2199 (MethodProxy*)PyObject_GetAttr( (PyObject*)self, PyStrings::gFitFCN );
2200
2201 // build new argument array
2202 PyObject* newArgs = PyTuple_New( argc );
2203 PyTuple_SET_ITEM( newArgs, 0, PyROOT_PyCapsule_New( (void*)FitterPyCallback, NULL, NULL ) );
2204 for ( int iarg = 1; iarg < argc; ++iarg ) {
2205 PyObject* pyarg = PyTuple_GET_ITEM( args, iarg );
2206 Py_INCREF( pyarg );
2207 PyTuple_SET_ITEM( newArgs, iarg, pyarg );
2208 }
2209
2210 // re-run
2211 PyObject* result = PyObject_CallObject( (PyObject*)method, newArgs );
2212
2213 // done, may have worked, if not: 0 is returned
2214 Py_DECREF( newArgs );
2215 Py_DECREF( method );
2216 return result;
2217 }
2218 };
2219
2220
2221//- TFile::Get -----------------------------------------------------------------
2222 PyObject* TFileGetAttr( PyObject* self, PyObject* attr )
2223 {
2224 // Pythonization of TFile::Get that raises AttributeError on failure.
2225 PyObject* result = CallPyObjMethod( self, "Get", attr );
2226 if ( !result )
2227 return result;
2228
2229 if ( !PyObject_IsTrue( result ) ) {
2230 PyObject* astr = PyObject_Str( attr );
2231 PyErr_Format( PyExc_AttributeError, "TFile object has no attribute \'%s\'",
2232 PyROOT_PyUnicode_AsString( astr ) );
2233 Py_DECREF( astr );
2234 Py_DECREF( result );
2235 return nullptr;
2236 }
2237
2238 // caching behavior seems to be more clear to the user; can always override said
2239 // behavior (i.e. re-read from file) with an explicit Get() call
2240 PyObject_SetAttr( self, attr, result );
2241 return result;
2242 }
2243
2244// This is done for TFile, but Get() is really defined in TDirectoryFile and its base
2245// TDirectory suffers from a similar problem. Nevertheless, the TFile case is by far
2246// the most common, so we'll leave it at this until someone asks for one of the bases
2247// to be pythonized.
2248 PyObject* TDirectoryFileGet( ObjectProxy* self, PyObject* pynamecycle )
2249 {
2250 // Pythonization of TDirectoryFile::Get that handles non-TObject deriveds
2251 if ( ! ObjectProxy_Check( self ) ) {
2252 PyErr_SetString( PyExc_TypeError,
2253 "TDirectoryFile::Get must be called with a TDirectoryFile instance as first argument" );
2254 return nullptr;
2255 }
2256
2257 TDirectoryFile* dirf =
2259 if ( !dirf ) {
2260 PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
2261 return nullptr;
2262 }
2263
2264 const char* namecycle = PyROOT_PyUnicode_AsString( pynamecycle );
2265 if ( !namecycle )
2266 return nullptr; // TypeError already set
2267
2268 TKey* key = dirf->GetKey( namecycle );
2269 if ( key ) {
2270 void* addr = dirf->GetObjectChecked( namecycle, key->GetClassName() );
2271 return BindCppObjectNoCast( addr,
2273 }
2274
2275 // no key? for better or worse, call normal Get()
2276 void* addr = dirf->Get( namecycle );
2277 return BindCppObject( addr, (Cppyy::TCppType_t)Cppyy::GetScope( "TObject" ), kFALSE );
2278 }
2279
2280 //- Pretty printing with cling::PrintValue
2281 PyObject *ClingPrintValue(ObjectProxy *self)
2282 {
2283 PyObject *cppname = PyObject_GetAttrString((PyObject *)self, "__cppname__");
2284 if (!PyROOT_PyUnicode_Check(cppname))
2285 return 0;
2286 std::string className = PyROOT_PyUnicode_AsString(cppname);
2287 Py_XDECREF(cppname);
2288
2289 std::string printResult = gInterpreter->ToString(className.c_str(), self->GetObject());
2290 if (printResult.find("@0x") == 0) {
2291 // Fall back to __repr__ if we just get an address from cling
2292 auto method = PyObject_GetAttrString((PyObject*)self, "__repr__");
2293 auto res = PyObject_CallObject(method, nullptr);
2294 Py_DECREF(method);
2295 return res;
2296 } else {
2297 return PyROOT_PyUnicode_FromString(printResult.c_str());
2298 }
2299 }
2300
2301 //- Adding array interface to classes ---------------
2302 void AddArrayInterface(PyObject *pyclass, PyCFunction func)
2303 {
2304 // Add a getter for the array interface dict to the class.
2305 Utility::AddToClass(pyclass, "_get__array_interface__", func, METH_NOARGS);
2306 // Add the dictionary as property to the class so that it updates automatically if accessed.
2307 // Since we are not able to add a property easily from C++, we do this in Python.
2308
2309 // We return early if the module does not have the function to add the property, which
2310 // is the case if cppyy is invoked directly and not through PyROOT.
2311 if (!PyObject_HasAttrString(gRootModule, "_add__array_interface__")) return;
2312
2313 auto f = PyObject_GetAttrString(gRootModule, "_add__array_interface__");
2314 auto r = PyObject_CallFunction(f, (char*)"O", pyclass);
2315 Py_DECREF(f);
2316 Py_DECREF(r);
2317 }
2318
2319 template <typename T, char typestr>
2320 PyObject *ArrayInterface(ObjectProxy *self)
2321 {
2322 T *cobj = reinterpret_cast<T*>(self->GetObject());
2323
2324 // Create array interface dict
2325 auto dict = PyDict_New();
2326
2327 // Version
2328 auto pyversion = PyLong_FromLong(3);
2329 PyDict_SetItemString(dict, "version", pyversion);
2330 Py_DECREF(pyversion);
2331
2332 // Type string
2333 #ifdef R__BYTESWAP
2334 const char endianess = '<';
2335#else
2336 const char endianess = '>';
2337#endif
2338 const UInt_t bytes = sizeof(typename T::value_type);
2339 auto pytypestr = PyROOT_PyUnicode_FromString(TString::Format("%c%c%i", endianess, typestr, bytes).Data());
2340 PyDict_SetItemString(dict, "typestr", pytypestr);
2341 Py_DECREF(pytypestr);
2342
2343 // Shape
2344 auto pysize = PyLong_FromLong(cobj->size());
2345 auto pyshape = PyTuple_Pack(1, pysize);
2346 PyDict_SetItemString(dict, "shape", pyshape);
2347 Py_DECREF(pysize);
2348 Py_DECREF(pyshape);
2349
2350 // Pointer
2351 auto ptr = reinterpret_cast<unsigned long long>(cobj->data());
2352 // Numpy breaks for data pointer of 0 even though the array is empty.
2353 // We set the pointer to 1 but the value itself is arbitrary and never accessed.
2354 if (cobj->empty()) ptr = 1;
2355 auto pyptr = PyLong_FromUnsignedLongLong(ptr);
2356 auto pydata = PyTuple_Pack(2, pyptr, Py_False);
2357 PyDict_SetItemString(dict, "data", pydata);
2358 Py_DECREF(pyptr);
2359 Py_DECREF(pydata);
2360
2361 return dict;
2362 }
2363
2364 //- simplistic len() functions -------------------------------------------------
2365 PyObject* ReturnThree( ObjectProxy*, PyObject* ) {
2366 return PyInt_FromLong( 3 );
2367 }
2368
2369 PyObject* ReturnTwo( ObjectProxy*, PyObject* ) {
2370 return PyInt_FromLong( 2 );
2371 }
2372
2373} // unnamed namespace
2374
2375
2376//- public functions -----------------------------------------------------------
2377Bool_t PyROOT::Pythonize( PyObject* pyclass, const std::string& name )
2378{
2379// Add pre-defined pythonizations (for STL and ROOT) to classes based on their
2380// signature and/or class name.
2381 if ( pyclass == 0 )
2382 return kFALSE;
2383
2384 // add pretty printing
2385 Utility::AddToClass(pyclass, "__str__", (PyCFunction)ClingPrintValue);
2386
2387 //- method name based pythonization --------------------------------------------
2388
2389 // for smart pointer style classes (note fall-through)
2390 if ( HasAttrDirect( pyclass, PyStrings::gDeref ) ) {
2391 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) DeRefGetAttr, METH_O );
2392 } else if ( HasAttrDirect( pyclass, PyStrings::gFollow ) ) {
2393 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) FollowGetAttr, METH_O );
2394 }
2395
2396// for STL containers, and user classes modeled after them
2397 if ( HasAttrDirect( pyclass, PyStrings::gSize ) )
2398 Utility::AddToClass( pyclass, "__len__", "size" );
2399
2400// like-wise, some typical container sizings
2401 if ( HasAttrDirect( pyclass, PyStrings::gGetSize ) )
2402 Utility::AddToClass( pyclass, "__len__", "GetSize" );
2403
2404 if ( HasAttrDirect( pyclass, PyStrings::ggetSize ) )
2405 Utility::AddToClass( pyclass, "__len__", "getSize" );
2406
2407 if ( HasAttrDirect( pyclass, PyStrings::gBegin ) && HasAttrDirect( pyclass, PyStrings::gEnd ) ) {
2408 // some classes may not have dicts for their iterators, making begin/end useless
2409 PyObject* pyfullname = PyObject_GetAttr( pyclass, PyStrings::gCppName );
2410 if ( ! pyfullname ) pyfullname = PyObject_GetAttr( pyclass, PyStrings::gName );
2411 TClass* klass = TClass::GetClass( PyROOT_PyUnicode_AsString( pyfullname ) );
2412 Py_DECREF( pyfullname );
2413
2414 if (!klass->InheritsFrom(TCollection::Class())) {
2415 // TCollection has a begin and end method so that they can be used in
2416 // the C++ range expression. However, unlike any other use of TIter,
2417 // TCollection::begin must include the first iteration. PyROOT is
2418 // handling TIter as a special case (as it should) and also does this
2419 // first iteration (via the first call to Next to get the first element)
2420 // and thus using begin in this case lead to the first element being
2421 // forgotten by PyROOT.
2422 // i.e. Don't search for begin in TCollection since we can not use.'
2423
2424 TMethod* meth = klass->GetMethodAllAny( "begin" );
2425
2426 TClass* iklass = 0;
2427 if ( meth ) {
2429 iklass = TClass::GetClass( meth->GetReturnTypeNormalizedName().c_str() );
2430 gErrorIgnoreLevel = oldl;
2431 }
2432
2433 if ( iklass && iklass->GetClassInfo() ) {
2434 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)StlSequenceIter;
2435 Utility::AddToClass( pyclass, "__iter__", (PyCFunction) StlSequenceIter, METH_NOARGS );
2436 } else if ( HasAttrDirect( pyclass, PyStrings::gGetItem ) && HasAttrDirect( pyclass, PyStrings::gLen ) ) {
2437 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2438 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2439 }
2440 }
2441 }
2442
2443// search for global comparator overloads (may fail; not sure whether it isn't better to
2444// do this lazily just as is done for math operators, but this interplays nicely with the
2445// generic versions)
2446 Utility::AddBinaryOperator( pyclass, "==", "__eq__" );
2447 Utility::AddBinaryOperator( pyclass, "!=", "__ne__" );
2448
2449// map operator==() through GenObjectIsEqual to allow comparison to None (kTRUE is to
2450// require that the located method is a MethodProxy; this prevents circular calls as
2451// GenObjectIsEqual is no MethodProxy)
2452 if ( HasAttrDirect( pyclass, PyStrings::gEq, kTRUE ) ) {
2453 Utility::AddToClass( pyclass, "__cpp_eq__", "__eq__" );
2454 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) GenObjectIsEqual, METH_O );
2455 }
2456
2457// map operator!=() through GenObjectIsNotEqual to allow comparison to None (see note
2458// on kTRUE above for __eq__)
2459 if ( HasAttrDirect( pyclass, PyStrings::gNe, kTRUE ) ) {
2460 Utility::AddToClass( pyclass, "__cpp_ne__", "__ne__" );
2461 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) GenObjectIsNotEqual, METH_O );
2462 }
2463
2464
2465//- class name based pythonization ---------------------------------------------
2466
2467 if ( name == "TObject" ) {
2468 // support for the 'in' operator
2469 Utility::AddToClass( pyclass, "__contains__", (PyCFunction) TObjectContains, METH_O );
2470
2471 // comparing for lists
2472 Utility::AddToClass( pyclass, "__cmp__", (PyCFunction) TObjectCompare, METH_O );
2473 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) TObjectIsEqual, METH_O );
2474 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) TObjectIsNotEqual, METH_O );
2475
2476 }
2477
2478 else if ( name == "TClass" ) {
2479 // make DynamicCast return a usable python object, rather than void*
2480 Utility::AddToClass( pyclass, "_TClass__DynamicCast", "DynamicCast" );
2481 Utility::AddToClass( pyclass, "DynamicCast", (PyCFunction) TClassDynamicCast );
2482
2483 // the following cast is easier to use (reads both ways)
2484 Utility::AddToClass( pyclass, "StaticCast", (PyCFunction) TClassStaticCast );
2485
2486 }
2487
2488 else if ( name == "TCollection" ) {
2489 Utility::AddToClass( pyclass, "append", "Add" );
2490 Utility::AddToClass( pyclass, "extend", (PyCFunction) TCollectionExtend, METH_O );
2491 Utility::AddToClass( pyclass, "remove", (PyCFunction) TCollectionRemove, METH_O );
2492 Utility::AddToClass( pyclass, "__add__", (PyCFunction) TCollectionAdd, METH_O );
2493 Utility::AddToClass( pyclass, "__imul__", (PyCFunction) TCollectionIMul, METH_O );
2494 Utility::AddToClass( pyclass, "__mul__", (PyCFunction) TCollectionMul, METH_O );
2495 Utility::AddToClass( pyclass, "__rmul__", (PyCFunction) TCollectionMul, METH_O );
2496
2497 Utility::AddToClass( pyclass, "count", (PyCFunction) TCollectionCount, METH_O );
2498
2499 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)TCollectionIter;
2500 Utility::AddToClass( pyclass, "__iter__", (PyCFunction)TCollectionIter, METH_NOARGS );
2501
2502 }
2503
2504 else if ( name == "TSeqCollection" ) {
2505 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) TSeqCollectionGetItem, METH_O );
2506 Utility::AddToClass( pyclass, "__setitem__", (PyCFunction) TSeqCollectionSetItem );
2507 Utility::AddToClass( pyclass, "__delitem__", (PyCFunction) TSeqCollectionDelItem, METH_O );
2508
2509 Utility::AddToClass( pyclass, "insert", (PyCFunction) TSeqCollectionInsert );
2510 Utility::AddToClass( pyclass, "pop", (PyCFunction) TSeqCollectionPop );
2511 Utility::AddToClass( pyclass, "reverse", (PyCFunction) TSeqCollectionReverse, METH_NOARGS );
2512 Utility::AddToClass( pyclass, "sort", (PyCFunction) TSeqCollectionSort,
2513 METH_VARARGS | METH_KEYWORDS );
2514
2515 Utility::AddToClass( pyclass, "index", (PyCFunction) TSeqCollectionIndex, METH_O );
2516
2517 }
2518
2519 else if ( name == "TObjArray" ) {
2520 Utility::AddToClass( pyclass, "__len__", (PyCFunction) TObjArrayLen, METH_NOARGS );
2521 }
2522
2523 else if ( name == "TClonesArray" ) {
2524 // restore base TSeqCollection operator[] to prevent random object creation (it's
2525 // functionality is equivalent to the operator[](int) const of TClonesArray, but
2526 // there's no guarantee it'll be selected over the non-const version)
2527 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) TSeqCollectionGetItem, METH_O );
2528
2529 // this setitem should be used with as much care as the C++ one
2530 Utility::AddToClass( pyclass, "__setitem__", (PyCFunction) TClonesArraySetItem );
2531
2532 }
2533
2534 else if ( IsTemplatedSTLClass( name, "vector" ) || (name.find("ROOT::VecOps::RVec<") == 0) ) {
2535
2536 if ( HasAttrDirect( pyclass, PyStrings::gLen ) && HasAttrDirect( pyclass, PyStrings::gAt ) ) {
2537 Utility::AddToClass( pyclass, "_vector__at", "at" );
2538 // remove iterator that was set earlier (checked __getitem__ will do the trick)
2539 if ( HasAttrDirect( pyclass, PyStrings::gIter ) )
2540 PyObject_DelAttr( pyclass, PyStrings::gIter );
2541 } else if ( HasAttrDirect( pyclass, PyStrings::gGetItem ) ) {
2542 Utility::AddToClass( pyclass, "_vector__at", "__getitem__" ); // unchecked!
2543 }
2544
2545 // vector-optimized iterator protocol
2546 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)vector_iter;
2547
2548 // helpers for iteration
2549 TypedefInfo_t* ti = gInterpreter->TypedefInfo_Factory( (name+"::value_type").c_str() );
2550 if ( gInterpreter->TypedefInfo_IsValid( ti ) ) {
2551 PyObject* pyvalue_size = PyLong_FromLong( gInterpreter->TypedefInfo_Size( ti ) );
2552 PyObject_SetAttrString( pyclass, "value_size", pyvalue_size );
2553 Py_DECREF( pyvalue_size );
2554
2555 PyObject* pyvalue_type = PyROOT_PyUnicode_FromString( gInterpreter->TypedefInfo_TrueName( ti ) );
2556 PyObject_SetAttrString( pyclass, "value_type", pyvalue_type );
2557 Py_DECREF( pyvalue_type );
2558 }
2559 gInterpreter->TypedefInfo_Delete( ti );
2560
2561 // provide a slice-able __getitem__, if possible
2562 if ( HasAttrDirect( pyclass, PyStrings::gVectorAt ) )
2563 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) VectorGetItem, METH_O );
2564
2565 // std::vector<bool> is a special case in C++
2566 std::string::size_type pos = name.find( "vector<bool" ); // to cover all variations
2567 if ( pos == 0 /* at beginning */ || pos == 5 /* after std:: */ ) {
2568 Utility::AddToClass( pyclass, "__setitem__", (PyCFunction) VectorBoolSetItem );
2569 }
2570
2571 // add array interface for STL vectors
2572 if (name.find("ROOT::VecOps::RVec<") == 0) {
2573 } else if (name == "vector<float>") {
2574 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<std::vector<float>, 'f'>);
2575 } else if (name == "vector<double>") {
2576 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<std::vector<double>, 'f'>);
2577 } else if (name == "vector<int>") {
2578 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<std::vector<int>, 'i'>);
2579 } else if (name == "vector<unsigned int>") {
2580 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<std::vector<unsigned int>, 'u'>);
2581 } else if (name == "vector<long>") {
2582 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<std::vector<long>, 'i'>);
2583 } else if (name == "vector<unsigned long>") {
2584 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<std::vector<unsigned long>, 'u'>);
2585 }
2586
2587 // add array interface for RVecs
2588 if (name.find("ROOT::VecOps::RVec<") != 0) {
2589 } else if (name == "ROOT::VecOps::RVec<float>") {
2590 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<ROOT::VecOps::RVec<float>, 'f'>);
2591 } else if (name == "ROOT::VecOps::RVec<double>") {
2592 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<ROOT::VecOps::RVec<double>, 'f'>);
2593 } else if (name == "ROOT::VecOps::RVec<int>") {
2594 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<ROOT::VecOps::RVec<int>, 'i'>);
2595 } else if (name == "ROOT::VecOps::RVec<unsigned int>") {
2596 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<ROOT::VecOps::RVec<unsigned int>, 'u'>);
2597 } else if (name == "ROOT::VecOps::RVec<long>") {
2598 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<ROOT::VecOps::RVec<long>, 'i'>);
2599 } else if (name == "ROOT::VecOps::RVec<unsigned long>") {
2600 AddArrayInterface(pyclass, (PyCFunction)ArrayInterface<ROOT::VecOps::RVec<unsigned long>, 'u'>);
2601 }
2602 }
2603
2604 else if ( IsTemplatedSTLClass( name, "map" ) ) {
2605 Utility::AddToClass( pyclass, "__contains__", (PyCFunction) MapContains, METH_O );
2606
2607 }
2608
2609 else if ( IsTemplatedSTLClass( name, "pair" ) ) {
2610 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) PairUnpack, METH_O );
2611 Utility::AddToClass( pyclass, "__len__", (PyCFunction) ReturnTwo, METH_NOARGS );
2612
2613 }
2614
2615 else if ( name.find( "iterator" ) != std::string::npos ) {
2616 ((PyTypeObject*)pyclass)->tp_iternext = (iternextfunc)StlIterNext;
2617 Utility::AddToClass( pyclass, PYROOT__next__, (PyCFunction) StlIterNext, METH_NOARGS );
2618
2619 // special case, if operator== is a global overload and included in the dictionary
2620 if ( ! HasAttrDirect( pyclass, PyStrings::gCppEq, kTRUE ) )
2621 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) StlIterIsEqual, METH_O );
2622 if ( ! HasAttrDirect( pyclass, PyStrings::gCppNe, kTRUE ) )
2623 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) StlIterIsNotEqual, METH_O );
2624
2625 }
2626
2627 else if ( name == "string" || name == "std::string" ) {
2628 Utility::AddToClass( pyclass, "__repr__", (PyCFunction) StlStringRepr, METH_NOARGS );
2629 Utility::AddToClass( pyclass, "__str__", "c_str" );
2630 Utility::AddToClass( pyclass, "__cmp__", (PyCFunction) StlStringCompare, METH_O );
2631 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) StlStringIsEqual, METH_O );
2632 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) StlStringIsNotEqual, METH_O );
2633
2634 }
2635
2636 else if ( name == "TString" ) {
2637 Utility::AddToClass( pyclass, "__repr__", (PyCFunction) TStringRepr, METH_NOARGS );
2638 Utility::AddToClass( pyclass, "__str__", "Data" );
2639 Utility::AddToClass( pyclass, "__len__", "Length" );
2640
2641 Utility::AddToClass( pyclass, "__cmp__", "CompareTo" );
2642 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) TStringIsEqual, METH_O );
2643 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) TStringIsNotEqual, METH_O );
2644
2645 }
2646
2647 else if ( name == "TObjString" ) {
2648 Utility::AddToClass( pyclass, "__repr__", (PyCFunction) TObjStringRepr, METH_NOARGS );
2649 Utility::AddToClass( pyclass, "__str__", "GetName" );
2650 Utility::AddToClass( pyclass, "__len__", (PyCFunction) TObjStringLength, METH_NOARGS );
2651
2652 Utility::AddToClass( pyclass, "__cmp__", (PyCFunction) TObjStringCompare, METH_O );
2653 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) TObjStringIsEqual, METH_O );
2654 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) TObjStringIsNotEqual, METH_O );
2655
2656 }
2657
2658 else if ( name == "TIter" ) {
2659 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)PyObject_SelfIter;
2660 Utility::AddToClass( pyclass, "__iter__", (PyCFunction) PyObject_SelfIter, METH_NOARGS );
2661
2662 ((PyTypeObject*)pyclass)->tp_iternext = (iternextfunc)TIterNext;
2663 Utility::AddToClass( pyclass, PYROOT__next__, (PyCFunction) TIterNext, METH_NOARGS );
2664
2665 }
2666
2667 else if ( name == "TDirectory" ) {
2668 // note: this replaces the already existing TDirectory::GetObject()
2669 Utility::AddToClass( pyclass, "GetObject", (PyCFunction) TDirectoryGetObject );
2670
2671 // note: this replaces the already existing TDirectory::WriteObject()
2672 Utility::AddToClass( pyclass, "WriteObject", (PyCFunction) TDirectoryWriteObject );
2673
2674 }
2675
2676 else if ( name == "TDirectoryFile" ) {
2677 // add safety for non-TObject derived Get() results
2678 Utility::AddToClass( pyclass, "Get", (PyCFunction) TDirectoryFileGet, METH_O );
2679
2680 // Re-inject here too, since TDirectoryFile redefines GetObject
2681 Utility::AddToClass(pyclass, "GetObject", (PyCFunction)TDirectoryGetObject);
2682
2683 return kTRUE;
2684 }
2685
2686 else if ( name == "TTree" ) {
2687 // allow direct browsing of the tree
2688 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) TTreeGetAttr, METH_O );
2689
2690 // workaround for templated member Branch()
2691 MethodProxy* original =
2692 (MethodProxy*)PyObject_GetAttrFromDict( pyclass, PyStrings::gBranch );
2693 MethodProxy* method = MethodProxy_New( "Branch", new TTreeBranch( original ) );
2694 Py_DECREF( original ); original = 0;
2695
2696 PyObject_SetAttrString(
2697 pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
2698 Py_DECREF( method ); method = 0;
2699
2700 // workaround for templated member SetBranchAddress()
2701 original = (MethodProxy*)PyObject_GetAttrFromDict( pyclass, PyStrings::gSetBranchAddress );
2702 method = MethodProxy_New( "SetBranchAddress", new TTreeSetBranchAddress( original ) );
2703 Py_DECREF( original ); original = 0;
2704
2705 PyObject_SetAttrString(
2706 pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
2707 Py_DECREF( method ); method = 0;
2708
2709 }
2710
2711 else if ( name == "TChain" ) {
2712 // allow SetBranchAddress to take object directly, w/o needing AddressOf()
2713 MethodProxy* original =
2714 (MethodProxy*)PyObject_GetAttrFromDict( pyclass, PyStrings::gSetBranchAddress );
2715 MethodProxy* method = MethodProxy_New( "SetBranchAddress", new TChainSetBranchAddress( original ) );
2716 Py_DECREF( original ); original = 0;
2717
2718 PyObject_SetAttrString(
2719 pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
2720 Py_DECREF( method ); method = 0;
2721
2722 }
2723
2724 else if ( name.find("ROOT::RDataFrame") == 0 || name.find("ROOT::RDF::RInterface<") == 0 ) {
2725 PyObject_SetAttrString(pyclass, "AsNumpy",
2726 PyObject_GetAttrString( gRootModule, "_RDataFrameAsNumpy" ));
2727 }
2728
2729 else if ( name == "TStyle" ) {
2730 MethodProxy* ctor = (MethodProxy*)PyObject_GetAttr( pyclass, PyStrings::gInit );
2731 ctor->fMethodInfo->fFlags &= ~TCallContext::kIsCreator;
2732 Py_DECREF( ctor );
2733 }
2734
2735 else if ( name == "TH1" ) // allow hist *= scalar
2736 Utility::AddToClass( pyclass, "__imul__", (PyCFunction) THNIMul, METH_O );
2737
2738 else if ( name == "TF1" ) // allow instantiation with python callable
2739 Utility::AddToClass( pyclass, "__init__", new TF1InitWithPyFunc );
2740
2741 else if ( name == "TF2" ) // allow instantiation with python callable
2742 Utility::AddToClass( pyclass, "__init__", new TF2InitWithPyFunc );
2743
2744 else if ( name == "TF3" ) // allow instantiation with python callable
2745 Utility::AddToClass( pyclass, "__init__", new TF3InitWithPyFunc );
2746
2747 else if ( name == "TFunction" ) // allow direct call
2748 Utility::AddToClass( pyclass, "__call__", (PyCFunction) TFunctionCall );
2749
2750 else if ( name == "TMinuit" ) // allow call with python callable
2751 Utility::AddToClass( pyclass, "SetFCN", new TMinuitSetFCN );
2752
2753 else if ( name == "TFitter" ) // allow call with python callable (this is not correct)
2754 Utility::AddToClass( pyclass, "SetFCN", new TMinuitFitterSetFCN );
2755
2756 else if ( name == "Fitter" ) // really Fit::Fitter, allow call with python callable
2757 Utility::AddToClass( pyclass, "FitFCN", new TFitterFitFCN );
2758
2759 else if ( name == "TFile" ) {
2760 // TFile::Open really is a constructor, really
2761 PyObject* attr = PyObject_GetAttrString( pyclass, (char*)"Open" );
2762 if ( MethodProxy_Check( attr ) )
2763 ((MethodProxy*)attr)->fMethodInfo->fFlags |= TCallContext::kIsCreator;
2764 Py_XDECREF( attr );
2765
2766 // allow member-style access to entries in file
2767 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) TFileGetAttr, METH_O );
2768 }
2769
2770 else if ( name.substr(0,8) == "TVector3" ) {
2771 Utility::AddToClass( pyclass, "__len__", (PyCFunction) ReturnThree, METH_NOARGS );
2772 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2773 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2774
2775 }
2776
2777 else if ( name.substr(0,8) == "TVectorT" ) {
2778 // allow proper iteration
2779 Utility::AddToClass( pyclass, "__len__", "GetNoElements" );
2780 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2781 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2782 }
2783
2784 else if ( name.substr(0,6) == "TArray" && name != "TArray" ) { // allow proper iteration
2785 // __len__ is already set from GetSize()
2786 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2787 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2788 }
2789
2790// Make RooFit 'using' member functions available (not supported by dictionary)
2791 else if ( name == "RooDataHist" )
2792 Utility::AddUsingToClass( pyclass, "plotOn" );
2793
2794 else if ( name == "RooSimultaneous" )
2795 Utility::AddUsingToClass( pyclass, "plotOn" );
2796
2797 // TODO: store these on the pythonizations module, not on gRootModule
2798 // TODO: externalize this code and use update handlers on the python side
2799 PyObject* userPythonizations = PyObject_GetAttrString( gRootModule, "UserPythonizations" );
2800 PyObject* pythonizationScope = PyObject_GetAttrString( gRootModule, "PythonizationScope" );
2801
2802 std::vector< std::string > pythonization_scopes;
2803 pythonization_scopes.push_back( "__global__" );
2804
2805 std::string user_scope = PyROOT_PyUnicode_AsString( pythonizationScope );
2806 if ( user_scope != "__global__" ) {
2807 if ( PyDict_Contains( userPythonizations, pythonizationScope ) ) {
2808 pythonization_scopes.push_back( user_scope );
2809 }
2810 }
2811
2812 Bool_t pstatus = kTRUE;
2813
2814 for ( auto key = pythonization_scopes.cbegin(); key != pythonization_scopes.cend(); ++key ) {
2815 PyObject* tmp = PyDict_GetItemString( userPythonizations, key->c_str() );
2816 Py_ssize_t num_pythonizations = PyList_Size( tmp );
2817 PyObject* arglist = nullptr;
2818 if ( num_pythonizations )
2819 arglist = Py_BuildValue( "O,s", pyclass, name.c_str() );
2820 for ( Py_ssize_t i = 0; i < num_pythonizations; ++i ) {
2821 PyObject* pythonizor = PyList_GetItem( tmp, i );
2822 // TODO: detail error handling for the pythonizors
2823 PyObject* result = PyObject_CallObject( pythonizor, arglist );
2824 if ( !result ) {
2825 pstatus = kFALSE;
2826 break;
2827 } else
2828 Py_DECREF( result );
2829 }
2830 Py_XDECREF( arglist );
2831 }
2832
2833 Py_DECREF( userPythonizations );
2834 Py_DECREF( pythonizationScope );
2835
2836
2837// phew! all done ...
2838 return pstatus;
2839}
void Class()
Definition: Class.C:29
SVector< double, 2 > v
Definition: Dict.h:5
#define R__EXTERN
Definition: DllImport.h:27
PyLong_FromUnsignedLongLong
Definition: Executors.cxx:289
ROOT::R::TRInterface & r
Definition: Object.C:4
#define Py_TYPE(ob)
Definition: PyROOT.h:161
#define PYROOT__next__
Definition: PyROOT.h:103
#define PyInt_FromSsize_t
Definition: PyROOT.h:168
int Py_ssize_t
Definition: PyROOT.h:166
#define PyROOT_PyUnicode_Check
Definition: PyROOT.h:76
#define PyROOT_PyUnicode_AsString
Definition: PyROOT.h:78
#define PyInt_AsSsize_t
Definition: PyROOT.h:167
#define PyROOT_PySliceCast
Definition: PyROOT.h:154
static PyObject * PyROOT_PyCapsule_New(void *cobj, const char *, void(*destr)(void *))
Definition: PyROOT.h:90
#define PyROOT_PyUnicode_FromString
Definition: PyROOT.h:82
#define PyROOT_PyUnicode_FromStringAndSize
Definition: PyROOT.h:86
#define PyROOT_PyUnicode_Type
Definition: PyROOT.h:88
#define PyVarObject_HEAD_INIT(type, size)
Definition: PyROOT.h:159
#define PYROOT_IMPLEMENT_STRING_PYTHONIZATION(type, name)
Definition: Pythonize.cxx:1177
#define PYROOT_IMPLEMENT_STRING_PYTHONIZATION_CMP(type, name)
Definition: Pythonize.cxx:1226
static TClass * OP2TCLASS(PyROOT::ObjectProxy *pyobj)
Definition: Pythonize.cxx:59
#define d(i)
Definition: RSha256.hxx:102
#define f(i)
Definition: RSha256.hxx:104
static RooMathCoreReg dummy
int Int_t
Definition: RtypesCore.h:41
unsigned int UInt_t
Definition: RtypesCore.h:42
const Bool_t kFALSE
Definition: RtypesCore.h:88
long Long_t
Definition: RtypesCore.h:50
bool Bool_t
Definition: RtypesCore.h:59
double Double_t
Definition: RtypesCore.h:55
const Bool_t kTRUE
Definition: RtypesCore.h:87
R__EXTERN Int_t gErrorIgnoreLevel
Definition: TError.h:105
char name[80]
Definition: TGX11.cxx:109
#define gInterpreter
Definition: TInterpreter.h:553
#define pyname
Definition: TMCParticle.cxx:19
_object PyObject
Definition: TPyArg.h:20
Binding & operator=(OUT(*fun)(void))
const std::string & GetName() const
Definition: MethodProxy.h:45
std::vector< PyCallable * > Methods_t
Definition: MethodProxy.h:24
MethodInfo_t * fMethodInfo
Definition: MethodProxy.h:52
Cppyy::TCppType_t ObjectIsA() const
Definition: ObjectProxy.h:66
void * GetObject() const
Definition: ObjectProxy.h:47
void Set(void *address, EFlags flags=kNone)
Definition: ObjectProxy.h:33
virtual Int_t GetMaxArgs()=0
virtual Int_t GetPriority()=0
virtual PyObject * GetArgDefault(Int_t)=0
virtual PyObject * GetCoVarNames()=0
virtual PyObject * Call(ObjectProxy *&self, PyObject *args, PyObject *kwds, TCallContext *ctxt=0)=0
virtual PyObject * FromMemory(void *address)
Definition: Converters.cxx:135
virtual PyObject * Call(ObjectProxy *&, PyObject *args, PyObject *kwds, TCallContext *ctx=0)
preliminary check in case keywords are accidently used (they are ignored otherwise)
PyObject * PyBuffer_FromMemory(Bool_t *buf, Py_ssize_t size=-1)
static TPyBufferFactory * Instance()
A Branch for the case of an object.
Int_t GetID() const
TStreamerInfo * GetInfo() const
Get streamer info for the branch class.
TClass * GetCurrentClass()
Return a pointer to the current type of the data member corresponding to branch element.
virtual TClass * GetTargetClass()
char * GetObject() const
Return a pointer to our object.
A TTree is a list of TBranches.
Definition: TBranch.h:65
virtual TLeaf * GetLeaf(const char *name) const
Return pointer to the 1st Leaf named name in thisBranch.
Definition: TBranch.cxx:1892
virtual const char * GetClassName() const
Return the name of the user class whose content is stored in this branch, if any.
Definition: TBranch.cxx:1301
virtual char * GetAddress() const
Definition: TBranch.h:181
Int_t GetOffset() const
Definition: TBranch.h:203
TObjArray * GetListOfLeaves()
Definition: TBranch.h:215
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition: TClass.h:75
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition: TClass.cxx:4841
void * DynamicCast(const TClass *base, void *obj, Bool_t up=kTRUE)
Cast obj of this class type up to baseclass cl if up is true.
Definition: TClass.cxx:4778
Int_t Size() const
Return size of object of this class.
Definition: TClass.cxx:5483
ClassInfo_t * GetClassInfo() const
Definition: TClass.h:404
TMethod * GetMethodAllAny(const char *method)
Return pointer to method without looking at parameters.
Definition: TClass.cxx:4254
Bool_t InheritsFrom(const char *cl) const
Return kTRUE if this class inherits from a class with name "classname".
Definition: TClass.cxx:4737
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition: TClass.cxx:2895
An array of clone (identical) objects.
Definition: TClonesArray.h:32
TClass * GetClass() const
Definition: TClonesArray.h:56
virtual TObject * RemoveAt(Int_t idx)
Remove object at index idx.
Collection abstract base class.
Definition: TCollection.h:63
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
Definition: TCollection.h:182
A ROOT file is structured in Directories (like a file system).
virtual void * GetObjectChecked(const char *namecycle, const char *classname)
See documentation of TDirectoryFile::GetObjectCheck(const char *namecycle, const TClass *cl)
virtual TObject * Get(const char *namecycle)
Return pointer to object identified by namecycle.
virtual TKey * GetKey(const char *name, Short_t cycle=9999) const
Return pointer to key with name,cycle.
Describe directory structure in memory.
Definition: TDirectory.h:34
virtual Int_t WriteObjectAny(const void *, const char *, const char *, Option_t *="", Int_t=0)
Definition: TDirectory.h:205
virtual void * GetObjectChecked(const char *namecycle, const char *classname)
See documentation of TDirectory::GetObjectCheck(const char *namecycle, const TClass *cl)
Definition: TDirectory.cxx:868
std::string GetReturnTypeNormalizedName() const
Get the normalized name of the return type.
Definition: TFunction.cxx:154
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition: TKey.h:24
virtual const char * GetClassName() const
Definition: TKey.h:71
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition: TLeaf.h:49
virtual void * GetValuePointer() const
Definition: TLeaf.h:117
virtual const char * GetTypeName() const
Definition: TLeaf.h:118
virtual TLeaf * GetLeafCount() const
If this leaf stores a variable-sized array or a multi-dimensional array whose last dimension has vari...
Definition: TLeaf.h:103
virtual Int_t GetNdata() const
Definition: TLeaf.h:115
TBranch * GetBranch() const
Definition: TLeaf.h:99
virtual Int_t GetLenStatic() const
Return the fixed length of this leaf.
Definition: TLeaf.h:111
Each ROOT class (see TClass) has a linked list of methods.
Definition: TMethod.h:38
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
An array of TObjects.
Definition: TObjArray.h:37
TObject * Last() const
Return the object in the last filled slot. Returns 0 if no entries.
Definition: TObjArray.cxx:505
TObject * First() const
Return the object in the first slot.
Definition: TObjArray.cxx:495
TObject * At(Int_t idx) const
Definition: TObjArray.h:166
Collectable string class.
Definition: TObjString.h:28
Mother of all ROOT objects.
Definition: TObject.h:37
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:443
Sequenceable collection abstract base class.
virtual TObject * RemoveAt(Int_t idx)
virtual void AddAt(TObject *obj, Int_t idx)=0
virtual void Add(TObject *obj)
virtual TObject * At(Int_t idx) const =0
TObjArray * GetElements() const
Basic string class.
Definition: TString.h:131
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition: TString.cxx:2311
A TTree represents a columnar dataset.
Definition: TTree.h:71
TCppScope_t gGlobalScope
Definition: Cppyy.cxx:64
TCppScope_t TCppType_t
Definition: Cppyy.h:16
TCppScope_t GetScope(const std::string &scope_name)
Definition: Cppyy.cxx:193
ptrdiff_t TCppMethod_t
Definition: Cppyy.h:18
std::string GetFinalName(TCppType_t type)
Definition: Cppyy.cxx:581
TCppObject_t Construct(TCppType_t type)
Definition: Cppyy.cxx:282
R__EXTERN PyObject * gIter
Definition: PyStrings.h:28
R__EXTERN PyObject * gSetFCN
Definition: PyStrings.h:58
R__EXTERN PyObject * gSecond
Definition: PyStrings.h:47
R__EXTERN PyObject * gClass
Definition: PyStrings.h:18
R__EXTERN PyObject * gCppEq
Definition: PyStrings.h:19
R__EXTERN PyObject * gAt
Definition: PyStrings.h:43
R__EXTERN PyObject * gName
Definition: PyStrings.h:33
R__EXTERN PyObject * gEq
Definition: PyStrings.h:24
R__EXTERN PyObject * gSize
Definition: PyStrings.h:48
R__EXTERN PyObject * gGetSize
Definition: PyStrings.h:49
R__EXTERN PyObject * gDict
Definition: PyStrings.h:22
R__EXTERN PyObject * gLen
Definition: PyStrings.h:29
R__EXTERN PyObject * gFitFCN
Definition: PyStrings.h:55
R__EXTERN PyObject * gNe
Definition: PyStrings.h:35
R__EXTERN PyObject * gTClassDynCast
Definition: PyStrings.h:59
R__EXTERN PyObject * gGetItem
Definition: PyStrings.h:26
R__EXTERN PyObject * gBegin
Definition: PyStrings.h:44
R__EXTERN PyObject * gFollow
Definition: PyStrings.h:25
R__EXTERN PyObject * gInit
Definition: PyStrings.h:27
R__EXTERN PyObject * gCppNe
Definition: PyStrings.h:20
R__EXTERN PyObject * gEnd
Definition: PyStrings.h:45
R__EXTERN PyObject * gDeref
Definition: PyStrings.h:21
R__EXTERN PyObject * gFirst
Definition: PyStrings.h:46
R__EXTERN PyObject * gSetBranchAddress
Definition: PyStrings.h:57
R__EXTERN PyObject * gVectorAt
Definition: PyStrings.h:52
R__EXTERN PyObject * gCppName
Definition: PyStrings.h:34
R__EXTERN PyObject * ggetSize
Definition: PyStrings.h:50
R__EXTERN PyObject * gBranch
Definition: PyStrings.h:54
Bool_t AddBinaryOperator(PyObject *left, PyObject *right, const char *op, const char *label, const char *alt_label=NULL)
Install the named operator (op) into the left object's class if such a function exists as a global ov...
Definition: Utility.cxx:315
Bool_t AddUsingToClass(PyObject *pyclass, const char *method)
Helper to add base class methods to the derived class one (this covers the 'using' cases,...
Definition: Utility.cxx:261
int GetBuffer(PyObject *pyobject, char tc, int size, void *&buf, Bool_t check=kTRUE)
Retrieve a linear buffer pointer from the given pyobject.
Definition: Utility.cxx:561
Bool_t AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Add the given function to the class under name 'label'.
Definition: Utility.cxx:186
void * CreateWrapperMethod(PyObject *pyfunc, Long_t user, const char *retType, const std::vector< std::string > &signature, const char *callback)
Compile a function on the fly and return a function pointer for use on C-APIs.
Definition: Utility.cxx:869
const std::string ClassName(PyObject *pyobj)
Retrieve the class name from the given python object (which may be just an instance of the class).
Definition: Utility.cxx:724
PyObject * BindCppObject(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, Bool_t isRef=kFALSE)
if the object is a null pointer, return a typed one (as needed for overloading)
PyObject * GetScopeProxy(Cppyy::TCppScope_t)
Retrieve scope proxy from the known ones.
void TMinuitPyCallback(void *vpyfunc, Long_t, Int_t &a0, Double_t *a1, Double_t &a2, Double_t *a3, Int_t a4)
Definition: Pythonize.cxx:1769
Bool_t ObjectProxy_Check(T *object)
Definition: ObjectProxy.h:91
PyTypeObject ObjectProxy_Type
MethodProxy * MethodProxy_New(const std::string &name, std::vector< PyCallable * > &methods)
Definition: MethodProxy.h:75
Bool_t MethodProxy_Check(T *object)
Definition: MethodProxy.h:63
PyObject * CreateScopeProxy(Cppyy::TCppScope_t)
Convenience function with a lookup first through the known existing proxies.
TConverter * CreateConverter(const std::string &fullType, Long_t size=-1)
PyObject * TTreeGetAttr(ObjectProxy *self, PyObject *pyname)
Definition: Pythonize.cxx:1405
R__EXTERN PyObject * gRootModule
Definition: ObjectProxy.cxx:39
double TFNPyCallback(void *vpyfunc, Long_t npar, double *a0, double *a1)
Definition: Pythonize.cxx:1799
PyObject * BindCppObjectNoCast(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, Bool_t isRef=kFALSE, Bool_t isValue=kFALSE)
only known or knowable objects will be bound (null object is ok)
Bool_t Pythonize(PyObject *pyclass, const std::string &name)
Definition: Pythonize.cxx:2377
double T(double x)
Definition: ChebyshevPol.h:34
static constexpr double s
Definition: tree.py:1
MethodProxy::Methods_t fMethods
Definition: MethodProxy.h:32
auto * l
Definition: textangle.C:4
#define org(otri, vertexptr)
Definition: triangle.c:1037