Logo ROOT   6.16/01
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 PyTypeObject VectorIter_Type = {
923 PyVarObject_HEAD_INIT( &PyType_Type, 0 )
924 (char*)"ROOT.vectoriter", // tp_name
925 sizeof(vectoriterobject), // tp_basicsize
926 0,
927 (destructor)vectoriter_dealloc, // tp_dealloc
928 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
929 Py_TPFLAGS_DEFAULT |
930 Py_TPFLAGS_HAVE_GC, // tp_flags
931 0,
932 (traverseproc)vectoriter_traverse, // tp_traverse
933 0, 0, 0,
934 PyObject_SelfIter, // tp_iter
935 (iternextfunc)vectoriter_iternext, // tp_iternext
936 0, // tp_methods
937 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
938#if PY_VERSION_HEX >= 0x02030000
939 , 0 // tp_del
940#endif
941#if PY_VERSION_HEX >= 0x02060000
942 , 0 // tp_version_tag
943#endif
944#if PY_VERSION_HEX >= 0x03040000
945 , 0 // tp_finalize
946#endif
947 };
948
949 static PyObject* vector_iter( PyObject* v ) {
950 vectoriterobject* vi = PyObject_GC_New( vectoriterobject, &VectorIter_Type );
951 if ( ! vi ) return NULL;
952
953 Py_INCREF( v );
954 vi->vi_vector = v;
955
956 PyObject* pyvalue_type = PyObject_GetAttrString( (PyObject*)Py_TYPE(v), "value_type" );
957 PyObject* pyvalue_size = PyObject_GetAttrString( (PyObject*)Py_TYPE(v), "value_size" );
958
959 if ( pyvalue_type && pyvalue_size ) {
960 PyObject* pydata = CallPyObjMethod( v, "data" );
961 if ( !pydata || Utility::GetBuffer( pydata, '*', 1, vi->vi_data, kFALSE ) == 0 )
962 vi->vi_data = nullptr;
963 Py_XDECREF( pydata );
964
965 vi->vi_converter = PyROOT::CreateConverter( PyROOT_PyUnicode_AsString( pyvalue_type ) );
966 vi->vi_stride = PyLong_AsLong( pyvalue_size );
967 } else {
968 PyErr_Clear();
969 vi->vi_data = nullptr;
970 vi->vi_converter = nullptr;
971 vi->vi_stride = 0;
972 }
973
974 Py_XDECREF( pyvalue_size );
975 Py_XDECREF( pyvalue_type );
976
977 vi->vi_len = vi->vi_pos = 0;
978 vi->vi_len = PySequence_Size( v );
979
980 PyObject_GC_Track( vi );
981 return (PyObject*)vi;
982 }
983
984
985 PyObject* VectorGetItem( ObjectProxy* self, PySliceObject* index )
986 {
987 // Implement python's __getitem__ for std::vector<>s.
988 if ( PySlice_Check( index ) ) {
989 if ( ! self->GetObject() ) {
990 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
991 return 0;
992 }
993
994 PyObject* pyclass = PyObject_GetAttr( (PyObject*)self, PyStrings::gClass );
995 PyObject* nseq = PyObject_CallObject( pyclass, NULL );
996 Py_DECREF( pyclass );
997
998 Py_ssize_t start, stop, step;
999 PySlice_GetIndices( (PyROOT_PySliceCast)index, PyObject_Length( (PyObject*)self ), &start, &stop, &step );
1000 for ( Py_ssize_t i = start; i < stop; i += step ) {
1001 PyObject* pyidx = PyInt_FromSsize_t( i );
1002 CallPyObjMethod( nseq, "push_back", CallPyObjMethod( (PyObject*)self, "_vector__at", pyidx ) );
1003 Py_DECREF( pyidx );
1004 }
1005
1006 return nseq;
1007 }
1008
1009 return CallSelfIndex( self, (PyObject*)index, "_vector__at" );
1010 }
1011
1012 PyObject* VectorBoolSetItem( ObjectProxy* self, PyObject* args )
1013 {
1014 // std::vector<bool> is a special-case in C++, and its return type depends on
1015 // the compiler: treat it special here as well
1016 int bval = 0; PyObject* idx = 0;
1017 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "Oi:__setitem__" ), &idx, &bval ) )
1018 return 0;
1019
1020 if ( ! self->GetObject() ) {
1021 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
1022 return 0;
1023 }
1024
1025 PyObject* pyindex = PyStyleIndex( (PyObject*)self, idx );
1026 if ( ! pyindex )
1027 return 0;
1028 int index = (int)PyLong_AsLong( pyindex );
1029 Py_DECREF( pyindex );
1030
1031 std::string clName = Cppyy::GetFinalName( self->ObjectIsA() );
1032 std::string::size_type pos = clName.find( "vector<bool" );
1033 if ( pos != 0 && pos != 5 /* following std:: */ ) {
1034 PyErr_Format( PyExc_TypeError,
1035 "require object of type std::vector<bool>, but %s given",
1036 Cppyy::GetFinalName( self->ObjectIsA() ).c_str() );
1037 return 0;
1038 }
1039
1040 // get hold of the actual std::vector<bool> (no cast, as vector is never a base)
1041 std::vector<bool>* vb = (std::vector<bool>*)self->GetObject();
1042
1043 // finally, set the value
1044 (*vb)[ index ] = (bool)bval;
1045
1046 Py_INCREF( Py_None );
1047 return Py_None;
1048 }
1049
1050//- map behavior as primitives ------------------------------------------------
1051 PyObject* MapContains( PyObject* self, PyObject* obj )
1052 {
1053 // Implement python's __contains__ for std::map<>s.
1054 PyObject* result = 0;
1055
1056 PyObject* iter = CallPyObjMethod( self, "find", obj );
1057 if ( ObjectProxy_Check( iter ) ) {
1058 PyObject* end = CallPyObjMethod( self, "end" );
1059 if ( ObjectProxy_Check( end ) ) {
1060 if ( ! PyObject_RichCompareBool( iter, end, Py_EQ ) ) {
1061 Py_INCREF( Py_True );
1062 result = Py_True;
1063 }
1064 }
1065 Py_XDECREF( end );
1066 }
1067 Py_XDECREF( iter );
1068
1069 if ( ! result ) {
1070 PyErr_Clear(); // e.g. wrong argument type, which should always lead to False
1071 Py_INCREF( Py_False );
1072 result = Py_False;
1073 }
1074
1075 return result;
1076 }
1077
1078//- STL container iterator support --------------------------------------------
1079 PyObject* StlSequenceIter( PyObject* self )
1080 {
1081 // Implement python's __iter__ for std::iterator<>s.
1082 PyObject* iter = CallPyObjMethod( self, "begin" );
1083 if ( iter ) {
1084 PyObject* end = CallPyObjMethod( self, "end" );
1085 if ( end )
1086 PyObject_SetAttr( iter, PyStrings::gEnd, end );
1087 Py_XDECREF( end );
1088
1089 // add iterated collection as attribute so its refcount stays >= 1 while it's being iterated over
1090 PyObject_SetAttr( iter, PyUnicode_FromString("_collection"), self );
1091 }
1092 return iter;
1093 }
1094
1095//- safe indexing for STL-like vector w/o iterator dictionaries ---------------
1096 PyObject* CheckedGetItem( PyObject* self, PyObject* obj )
1097 {
1098 // Implement a generic python __getitem__ for std::vector<>s that are missing
1099 // their std::vector<>::iterator dictionary. This is then used for iteration
1100 // by means of consecutive index.
1101 Bool_t inbounds = kFALSE;
1102 Py_ssize_t size = PySequence_Size( self );
1103 Py_ssize_t idx = PyInt_AsSsize_t( obj );
1104 if ( 0 <= idx && 0 <= size && idx < size )
1105 inbounds = kTRUE;
1106
1107 if ( inbounds ) {
1108 return CallPyObjMethod( self, "_getitem__unchecked", obj );
1109 } else if ( PyErr_Occurred() ) {
1110 // argument conversion problem: let method itself resolve anew and report
1111 PyErr_Clear();
1112 return CallPyObjMethod( self, "_getitem__unchecked", obj );
1113 } else {
1114 PyErr_SetString( PyExc_IndexError, "index out of range" );
1115 }
1116
1117 return 0;
1118 }
1119
1120//- pair as sequence to allow tuple unpacking ---------------------------------
1121 PyObject* PairUnpack( PyObject* self, PyObject* pyindex )
1122 {
1123 // For std::map<> iteration, unpack std::pair<>s into tuples for the loop.
1124 Long_t idx = PyLong_AsLong( pyindex );
1125 if ( idx == -1 && PyErr_Occurred() )
1126 return 0;
1127
1128 if ( ! ObjectProxy_Check( self ) || ! ((ObjectProxy*)self)->GetObject() ) {
1129 PyErr_SetString( PyExc_TypeError, "unsubscriptable object" );
1130 return 0;
1131 }
1132
1133 if ( (int)idx == 0 )
1134 return PyObject_GetAttr( self, PyStrings::gFirst );
1135 else if ( (int)idx == 1 )
1136 return PyObject_GetAttr( self, PyStrings::gSecond );
1137
1138 // still here? Trigger stop iteration
1139 PyErr_SetString( PyExc_IndexError, "out of bounds" );
1140 return 0;
1141 }
1142
1143//- string behavior as primitives ----------------------------------------------
1144#if PY_VERSION_HEX >= 0x03000000
1145// TODO: this is wrong, b/c it doesn't order
1146static int PyObject_Compare( PyObject* one, PyObject* other ) {
1147 return ! PyObject_RichCompareBool( one, other, Py_EQ );
1148}
1149#endif
1150 static inline PyObject* PyROOT_PyString_FromCppString( std::string* s ) {
1151 return PyROOT_PyUnicode_FromStringAndSize( s->c_str(), s->size() );
1152 }
1153
1154 static inline PyObject* PyROOT_PyString_FromCppString( TString* s ) {
1155 return PyROOT_PyUnicode_FromStringAndSize( s->Data(), s->Length() );
1156 }
1157
1158 static inline PyObject* PyROOT_PyString_FromCppString( TObjString* s ) {
1159 return PyROOT_PyUnicode_FromStringAndSize( s->GetString().Data(), s->GetString().Length() );
1160 }
1161
1162#define PYROOT_IMPLEMENT_STRING_PYTHONIZATION( type, name ) \
1163 inline PyObject* name##GetData( PyObject* self ) { \
1164 if ( PyROOT::ObjectProxy_Check( self ) ) { \
1165 type* obj = ((type*)((ObjectProxy*)self)->GetObject()); \
1166 if ( obj ) { \
1167 return PyROOT_PyString_FromCppString( obj ); \
1168 } else { \
1169 return ObjectProxy_Type.tp_str( self ); \
1170 } \
1171 } \
1172 PyErr_Format( PyExc_TypeError, "object mismatch (%s expected)", #type );\
1173 return 0; \
1174 } \
1175 \
1176 PyObject* name##StringRepr( PyObject* self ) \
1177 { \
1178 PyObject* data = name##GetData( self ); \
1179 if ( data ) { \
1180 PyObject* repr = PyROOT_PyUnicode_FromFormat( "\'%s\'", PyROOT_PyUnicode_AsString( data ) ); \
1181 Py_DECREF( data ); \
1182 return repr; \
1183 } \
1184 return 0; \
1185 } \
1186 \
1187 PyObject* name##StringIsEqual( PyObject* self, PyObject* obj ) \
1188 { \
1189 PyObject* data = name##GetData( self ); \
1190 if ( data ) { \
1191 PyObject* result = PyObject_RichCompare( data, obj, Py_EQ ); \
1192 Py_DECREF( data ); \
1193 return result; \
1194 } \
1195 return 0; \
1196 } \
1197 \
1198 PyObject* name##StringIsNotEqual( PyObject* self, PyObject* obj ) \
1199 { \
1200 PyObject* data = name##GetData( self ); \
1201 if ( data ) { \
1202 PyObject* result = PyObject_RichCompare( data, obj, Py_NE ); \
1203 Py_DECREF( data ); \
1204 return result; \
1205 } \
1206 return 0; \
1207 }
1208
1209 // Only define StlStringCompare:
1210 // TStringCompare is unused and generates a warning;
1211#define PYROOT_IMPLEMENT_STRING_PYTHONIZATION_CMP( type, name ) \
1212 PYROOT_IMPLEMENT_STRING_PYTHONIZATION( type, name ) \
1213 PyObject* name##StringCompare( PyObject* self, PyObject* obj ) \
1214 { \
1215 PyObject* data = name##GetData( self ); \
1216 int result = 0; \
1217 if ( data ) { \
1218 result = PyObject_Compare( data, obj ); \
1219 Py_DECREF( data ); \
1220 } \
1221 if ( PyErr_Occurred() ) \
1222 return 0; \
1223 return PyInt_FromLong( result ); \
1224 }
1225
1228
1229
1230//- TObjString behavior --------------------------------------------------------
1232
1233////////////////////////////////////////////////////////////////////////////////
1234/// Implementation of python __len__ for TObjString.
1235
1236 PyObject* TObjStringLength( PyObject* self )
1237 {
1238 PyObject* data = CallPyObjMethod( self, "GetName" );
1239 Py_ssize_t size = PySequence_Size( data );
1240 Py_DECREF( data );
1241 return PyInt_FromSsize_t( size );
1242 }
1243
1244
1245//- TIter behavior -------------------------------------------------------------
1246 PyObject* TIterNext( PyObject* self )
1247 {
1248 // Implementation of python __next__ (iterator protocol) for TIter.
1249 PyObject* next = CallPyObjMethod( self, "Next" );
1250
1251 if ( ! next )
1252 return 0;
1253
1254 if ( ! PyObject_IsTrue( next ) ) {
1255 Py_DECREF( next );
1256 PyErr_SetString( PyExc_StopIteration, "" );
1257 return 0;
1258 }
1259
1260 return next;
1261 }
1262
1263
1264//- STL iterator behavior ------------------------------------------------------
1265 PyObject* StlIterNext( PyObject* self )
1266 {
1267 // Python iterator protocol __next__ for STL forward iterators.
1268 PyObject* next = 0;
1269 PyObject* last = PyObject_GetAttr( self, PyStrings::gEnd );
1270
1271 if ( last != 0 ) {
1272 // handle special case of empty container (i.e. self is end)
1273 if ( PyObject_RichCompareBool( last, self, Py_EQ ) ) {
1274 PyErr_SetString( PyExc_StopIteration, "" );
1275 } else {
1276 PyObject* dummy = PyInt_FromLong( 1l );
1277 PyObject* iter = CallPyObjMethod( self, "__postinc__", dummy );
1278 Py_DECREF( dummy );
1279 if ( iter != 0 ) {
1280 if ( PyObject_RichCompareBool( last, iter, Py_EQ ) )
1281 PyErr_SetString( PyExc_StopIteration, "" );
1282 else
1283 next = CallPyObjMethod( iter, "__deref__" );
1284 } else {
1285 PyErr_SetString( PyExc_StopIteration, "" );
1286 }
1287 Py_XDECREF( iter );
1288 }
1289 } else {
1290 PyErr_SetString( PyExc_StopIteration, "" );
1291 }
1292
1293 Py_XDECREF( last );
1294 return next;
1295 }
1296
1297////////////////////////////////////////////////////////////////////////////////
1298/// Called if operator== not available (e.g. if a global overload as under gcc).
1299/// An exception is raised as the user should fix the dictionary.
1300
1301 PyObject* StlIterIsEqual( PyObject* self, PyObject* other )
1302 {
1303 return PyErr_Format( PyExc_LookupError,
1304 "No operator==(const %s&, const %s&) available in the dictionary!",
1305 Utility::ClassName( self ).c_str(), Utility::ClassName( other ).c_str() );
1306 }
1307
1308////////////////////////////////////////////////////////////////////////////////
1309/// Called if operator!= not available (e.g. if a global overload as under gcc).
1310/// An exception is raised as the user should fix the dictionary.
1311
1312 PyObject* StlIterIsNotEqual( PyObject* self, PyObject* other )
1313 {
1314 return PyErr_Format( PyExc_LookupError,
1315 "No operator!=(const %s&, const %s&) available in the dictionary!",
1316 Utility::ClassName( self ).c_str(), Utility::ClassName( other ).c_str() );
1317 }
1318
1319
1320//- TDirectory member templates ----------------------------------------------
1321 PyObject* TDirectoryGetObject( ObjectProxy* self, PyObject* args )
1322 {
1323 // Pythonization of TDirector::GetObject().
1324 PyObject* name = 0; ObjectProxy* ptr = 0;
1325 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "O!O!:TDirectory::GetObject" ),
1327 return 0;
1328
1329 TDirectory* dir =
1331
1332 if ( ! dir ) {
1333 PyErr_SetString( PyExc_TypeError,
1334 "TDirectory::GetObject must be called with a TDirectory instance as first argument" );
1335 return 0;
1336 }
1337
1338 void* address = dir->GetObjectChecked( PyROOT_PyUnicode_AsString( name ), OP2TCLASS(ptr) );
1339 if ( address ) {
1340 ptr->Set( address );
1341
1342 Py_INCREF( Py_None );
1343 return Py_None;
1344 }
1345
1346 PyErr_Format( PyExc_LookupError, "no such object, \"%s\"", PyROOT_PyUnicode_AsString( name ) );
1347 return 0;
1348 }
1349
1350////////////////////////////////////////////////////////////////////////////////
1351/// Type-safe version of TDirectory::WriteObjectAny, which is a template for
1352/// the same reason on the C++ side.
1353
1354 PyObject* TDirectoryWriteObject( ObjectProxy* self, PyObject* args )
1355 {
1356 ObjectProxy *wrt = 0; PyObject *name = 0, *option = 0;
1357 Int_t bufsize = 0;
1358 if ( ! PyArg_ParseTuple( args, const_cast< char* >( "O!O!|O!i:TDirectory::WriteObject" ),
1360 &PyROOT_PyUnicode_Type, &option, &bufsize ) )
1361 return 0;
1362
1363 TDirectory* dir =
1365
1366 if ( ! dir ) {
1367 PyErr_SetString( PyExc_TypeError,
1368 "TDirectory::WriteObject must be called with a TDirectory instance as first argument" );
1369 return 0;
1370 }
1371
1372 Int_t result = 0;
1373 if ( option != 0 ) {
1374 result = dir->WriteObjectAny( wrt->GetObject(), OP2TCLASS(wrt),
1376 } else {
1377 result = dir->WriteObjectAny(
1379 }
1380
1381 return PyInt_FromLong( (Long_t)result );
1382 }
1383
1384}
1385
1386
1387namespace PyROOT { // workaround for Intel icc on Linux
1388
1389//- TTree behavior ------------------------------------------------------------
1391 {
1392 // allow access to branches/leaves as if they are data members
1393 const char* name1 = PyROOT_PyUnicode_AsString( pyname );
1394 if ( ! name1 )
1395 return 0;
1396
1397 // get hold of actual tree
1398 TTree* tree =
1399 (TTree*)OP2TCLASS(self)->DynamicCast( TTree::Class(), self->GetObject() );
1400
1401 if ( ! tree ) {
1402 PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
1403 return 0;
1404 }
1405
1406 // deal with possible aliasing
1407 const char* name = tree->GetAlias( name1 );
1408 if ( ! name ) name = name1;
1409
1410 // search for branch first (typical for objects)
1411 TBranch* branch = tree->GetBranch( name );
1412 if ( ! branch ) {
1413 // for benefit of naming of sub-branches, the actual name may have a trailing '.'
1414 branch = tree->GetBranch( (std::string( name ) + '.' ).c_str() );
1415 }
1416
1417 if ( branch ) {
1418 // found a branched object, wrap its address for the object it represents
1419
1420 // for partial return of a split object
1421 if ( branch->InheritsFrom(TBranchElement::Class()) ) {
1422 TBranchElement* be = (TBranchElement*)branch;
1423 if ( be->GetCurrentClass() && (be->GetCurrentClass() != be->GetTargetClass()) && (0 <= be->GetID()) ) {
1424 Long_t offset = ((TStreamerElement*)be->GetInfo()->GetElements()->At(be->GetID()))->GetOffset();
1425 return BindCppObjectNoCast( be->GetObject() + offset, Cppyy::GetScope( be->GetCurrentClass()->GetName() ) );
1426 }
1427 }
1428
1429 // for return of a full object
1430 if ( branch->IsA() == TBranchElement::Class() || branch->IsA() == TBranchObject::Class() ) {
1431 TClass* klass = TClass::GetClass( branch->GetClassName() );
1432 if ( klass && branch->GetAddress() )
1433 return BindCppObjectNoCast( *(void**)branch->GetAddress(), Cppyy::GetScope( branch->GetClassName() ) );
1434
1435 // try leaf, otherwise indicate failure by returning a typed null-object
1436 TObjArray* leaves = branch->GetListOfLeaves();
1437 if ( klass && ! tree->GetLeaf( name ) &&
1438 ! (leaves->GetSize() && ( leaves->First() == leaves->Last() ) ) )
1439 return BindCppObjectNoCast( NULL, Cppyy::GetScope( branch->GetClassName() ) );
1440 }
1441 }
1442
1443 // if not, try leaf
1444 TLeaf* leaf = tree->GetLeaf( name );
1445 if ( branch && ! leaf ) {
1446 leaf = branch->GetLeaf( name );
1447 if ( ! leaf ) {
1448 TObjArray* leaves = branch->GetListOfLeaves();
1449 if ( leaves->GetSize() && ( leaves->First() == leaves->Last() ) ) {
1450 // i.e., if unambiguously only this one
1451 leaf = (TLeaf*)leaves->At( 0 );
1452 }
1453 }
1454 }
1455
1456 if ( leaf ) {
1457 // found a leaf, extract value and wrap
1458 if ( 1 < leaf->GetLenStatic() || leaf->GetLeafCount() ) {
1459 // array types
1460 std::string typeName = leaf->GetTypeName();
1461 TConverter* pcnv = CreateConverter( typeName + '*', leaf->GetNdata() );
1462
1463 void* address = 0;
1464 if ( leaf->GetBranch() ) address = (void*)leaf->GetBranch()->GetAddress();
1465 if ( ! address ) address = (void*)leaf->GetValuePointer();
1466
1467 PyObject* value = pcnv->FromMemory( &address );
1468 delete pcnv;
1469
1470 return value;
1471 } else if ( leaf->GetValuePointer() ) {
1472 // value types
1473 TConverter* pcnv = CreateConverter( leaf->GetTypeName() );
1474 PyObject* value = 0;
1475 if ( leaf->IsA() == TLeafElement::Class() || leaf->IsA() == TLeafObject::Class() )
1476 value = pcnv->FromMemory( (void*)*(void**)leaf->GetValuePointer() );
1477 else
1478 value = pcnv->FromMemory( (void*)leaf->GetValuePointer() );
1479 delete pcnv;
1480
1481 return value;
1482 }
1483 }
1484
1485 // confused
1486 PyErr_Format( PyExc_AttributeError,
1487 "\'%s\' object has no attribute \'%s\'", tree->IsA()->GetName(), name );
1488 return 0;
1489 }
1490
1491////////////////////////////////////////////////////////////////////////////////
1492
1493 class TTreeMemberFunction : public PyCallable {
1494 protected:
1495 TTreeMemberFunction( MethodProxy* org ) { Py_INCREF( org ); fOrg = org; }
1496 TTreeMemberFunction( const TTreeMemberFunction& t ) : PyCallable( t )
1497 {
1498 // Copy constructor; conform to python reference counting.
1499 Py_INCREF( t.fOrg );
1500 fOrg = t.fOrg;
1501 }
1502 TTreeMemberFunction& operator=( const TTreeMemberFunction& t )
1503 {
1504 // Assignment operator; conform to python reference counting.
1505 if ( &t != this ) {
1506 Py_INCREF( t.fOrg );
1507 Py_XDECREF( fOrg );
1508 fOrg = t.fOrg;
1509 }
1510 return *this;
1511 }
1512 ~TTreeMemberFunction() { Py_DECREF( fOrg ); fOrg = 0; }
1513
1514 public:
1515 virtual PyObject* GetSignature() { return PyROOT_PyUnicode_FromString( "(...)" ); }
1516 virtual PyObject* GetPrototype() { return PyObject_GetAttrString( (PyObject*)fOrg, (char*)"__doc__" ); }
1517 virtual Int_t GetPriority() { return 100; }
1518 virtual PyObject* GetCoVarNames() {
1519 PyObject* co_varnames = PyTuple_New( 1 /* self */ + 1 /* fake */ );
1520 PyTuple_SET_ITEM( co_varnames, 0, PyROOT_PyUnicode_FromString( "self" ) );
1521 PyTuple_SET_ITEM( co_varnames, 1, PyROOT_PyUnicode_FromString( "*args" ) );
1522 return co_varnames;
1523 }
1524 virtual PyObject* GetArgDefault( Int_t ) { return NULL; }
1525 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TTree" ); }
1526
1527 protected:
1528 MethodProxy* fOrg;
1529 };
1530
1531////////////////////////////////////////////////////////////////////////////////
1532
1533 class TTreeBranch : public TTreeMemberFunction {
1534 public:
1535 TTreeBranch( MethodProxy* org ) : TTreeMemberFunction( org ) {}
1536
1537 public:
1538 virtual Int_t GetMaxArgs() { return 5; }
1539 virtual PyCallable* Clone() { return new TTreeBranch( *this ); }
1540
1541 virtual PyObject* Call(
1542 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* /* ctxt */ )
1543 {
1544 // acceptable signatures:
1545 // ( const char*, void*, const char*, Int_t = 32000 )
1546 // ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
1547 // ( const char*, T**, Int_t = 32000, Int_t = 99 )
1548 int argc = PyTuple_GET_SIZE( args );
1549
1550 if ( 2 <= argc ) {
1551 TTree* tree =
1552 (TTree*)OP2TCLASS(self)->DynamicCast( TTree::Class(), self->GetObject() );
1553
1554 if ( ! tree ) {
1555 PyErr_SetString( PyExc_TypeError,
1556 "TTree::Branch must be called with a TTree instance as first argument" );
1557 return 0;
1558 }
1559
1560 PyObject *name = 0, *clName = 0, *leaflist = 0;
1561 PyObject *address = 0;
1562 PyObject *bufsize = 0, *splitlevel = 0;
1563
1564 // try: ( const char*, void*, const char*, Int_t = 32000 )
1565 if ( PyArg_ParseTuple( args, const_cast< char* >( "O!OO!|O!:Branch" ),
1567 &leaflist, &PyInt_Type, &bufsize ) ) {
1568
1569 void* buf = 0;
1570 if ( ObjectProxy_Check( address ) )
1571 buf = (void*)((ObjectProxy*)address)->GetObject();
1572 else
1573 Utility::GetBuffer( address, '*', 1, buf, kFALSE );
1574
1575 if ( buf != 0 ) {
1576 TBranch* branch = 0;
1577 if ( argc == 4 ) {
1578 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), buf,
1579 PyROOT_PyUnicode_AsString( leaflist ), PyInt_AS_LONG( bufsize ) );
1580 } else {
1581 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), buf,
1582 PyROOT_PyUnicode_AsString( leaflist ) );
1583 }
1584
1585 return BindCppObject( branch, "TBranch" );
1586 }
1587
1588 }
1589 PyErr_Clear();
1590
1591 // try: ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
1592 // or: ( const char*, T**, Int_t = 32000, Int_t = 99 )
1593 Bool_t bIsMatch = kFALSE;
1594 if ( PyArg_ParseTuple( args, const_cast< char* >( "O!O!O|O!O!:Branch" ),
1595 &PyROOT_PyUnicode_Type, &name, &PyROOT_PyUnicode_Type, &clName, &address,
1596 &PyInt_Type, &bufsize, &PyInt_Type, &splitlevel ) ) {
1597 bIsMatch = kTRUE;
1598 } else {
1599 PyErr_Clear(); clName = 0; // clName no longer used
1600 if ( PyArg_ParseTuple( args, const_cast< char* >( "O!O|O!O!" ),
1601 &PyROOT_PyUnicode_Type, &name, &address,
1602 &PyInt_Type, &bufsize, &PyInt_Type, &splitlevel ) ) {
1603 bIsMatch = kTRUE;
1604 } else
1605 PyErr_Clear();
1606 }
1607
1608 if ( bIsMatch == kTRUE ) {
1609 std::string klName = clName ? PyROOT_PyUnicode_AsString( clName ) : "";
1610 void* buf = 0;
1611
1612 if ( ObjectProxy_Check( address ) ) {
1613 if ( ((ObjectProxy*)address)->fFlags & ObjectProxy::kIsReference )
1614 buf = (void*)((ObjectProxy*)address)->fObject;
1615 else
1616 buf = (void*)&((ObjectProxy*)address)->fObject;
1617
1618 if ( ! clName ) {
1619 klName = OP2TCLASS((ObjectProxy*)address)->GetName();
1620 argc += 1;
1621 }
1622 } else
1623 Utility::GetBuffer( address, '*', 1, buf, kFALSE );
1624
1625 if ( buf != 0 && klName != "" ) {
1626 TBranch* branch = 0;
1627 if ( argc == 3 ) {
1628 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), klName.c_str(), buf );
1629 } else if ( argc == 4 ) {
1630 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), klName.c_str(), buf,
1631 PyInt_AS_LONG( bufsize ) );
1632 } else if ( argc == 5 ) {
1633 branch = tree->Branch( PyROOT_PyUnicode_AsString( name ), klName.c_str(), buf,
1634 PyInt_AS_LONG( bufsize ), PyInt_AS_LONG( splitlevel ) );
1635 }
1636
1637 return BindCppObject( branch, "TBranch" );
1638 }
1639 }
1640 }
1641
1642 // still here? Then call original Branch() to reach the other overloads:
1643 Py_INCREF( (PyObject*)self );
1644 fOrg->fSelf = self;
1645 PyObject* result = PyObject_Call( (PyObject*)fOrg, args, kwds );
1646 fOrg->fSelf = 0;
1647 Py_DECREF( (PyObject*)self );
1648
1649 return result;
1650 }
1651 };
1652
1653////////////////////////////////////////////////////////////////////////////////
1654
1655 class TTreeSetBranchAddress : public TTreeMemberFunction {
1656 public:
1657 TTreeSetBranchAddress( MethodProxy* org ) : TTreeMemberFunction( org ) {}
1658
1659 public:
1660 virtual PyObject* GetPrototype()
1661 {
1662 return PyROOT_PyUnicode_FromString( "TBranch* TTree::SetBranchAddress( ... )" );
1663 }
1664
1665 virtual Int_t GetMaxArgs() { return 2; }
1666 virtual PyCallable* Clone() { return new TTreeSetBranchAddress( *this ); }
1667
1668 virtual PyObject* Call(
1669 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* /* ctxt */ )
1670 {
1671 // acceptable signature:
1672 // ( const char*, void* )
1673 int argc = PyTuple_GET_SIZE( args );
1674
1675 if ( 2 == argc ) {
1676 TTree* tree =
1677 (TTree*)OP2TCLASS(self)->DynamicCast( TTree::Class(), self->GetObject() );
1678
1679 if ( ! tree ) {
1680 PyErr_SetString( PyExc_TypeError,
1681 "TTree::SetBranchAddress must be called with a TTree instance as first argument" );
1682 return 0;
1683 }
1684
1685 PyObject *name = 0, *address = 0;
1686
1687 // try: ( const char*, void* )
1688 if ( PyArg_ParseTuple( args, const_cast< char* >( "SO:SetBranchAddress" ),
1689 &name, &address ) ) {
1690
1691 void* buf = 0;
1692 if ( ObjectProxy_Check( address ) ) {
1693 if ( ((ObjectProxy*)address)->fFlags & ObjectProxy::kIsReference )
1694 buf = (void*)((ObjectProxy*)address)->fObject;
1695 else
1696 buf = (void*)&((ObjectProxy*)address)->fObject;
1697 } else
1698 Utility::GetBuffer( address, '*', 1, buf, kFALSE );
1699
1700 if ( buf != 0 ) {
1701 tree->SetBranchAddress( PyROOT_PyUnicode_AsString( name ), buf );
1702
1703 Py_INCREF( Py_None );
1704 return Py_None;
1705 }
1706 }
1707 }
1708
1709 // still here? Then call original Branch() to reach the other overloads:
1710 Py_INCREF( (PyObject*)self );
1711 fOrg->fSelf = self;
1712 PyObject* result = PyObject_Call( (PyObject*)fOrg, args, kwds );
1713 fOrg->fSelf = 0;
1714 Py_DECREF( (PyObject*)self );
1715
1716 return result;
1717 }
1718
1719 protected:
1720 virtual PyObject* ReportTypeError()
1721 {
1722 PyErr_SetString( PyExc_TypeError,
1723 "TTree::SetBranchAddress must be called with a TTree instance as first argument" );
1724 return 0;
1725 }
1726 };
1727
1728
1729// TChain overrides TTree's SetBranchAddress, so set it again (the python method only forwards
1730// onto a TTree*, so the C++ virtual function call will make sure the right method is used)
1731 class TChainSetBranchAddress : public TTreeSetBranchAddress {
1732 public:
1733 TChainSetBranchAddress( MethodProxy* org ) : TTreeSetBranchAddress( org ) {}
1734
1735 public:
1736 virtual PyObject* GetPrototype()
1737 {
1738 return PyROOT_PyUnicode_FromString( "TBranch* TChain::SetBranchAddress( ... )" );
1739 }
1740
1741 virtual Int_t GetMaxArgs() { return 2; }
1742 virtual PyCallable* Clone() { return new TChainSetBranchAddress( *this ); }
1743
1744 protected:
1745 virtual PyObject* ReportTypeError()
1746 {
1747 PyErr_SetString( PyExc_TypeError,
1748 "TChain::SetBranchAddress must be called with a TChain instance as first argument" );
1749 return 0;
1750 }
1751 };
1752
1753//- TMinuit behavior ----------------------------------------------------------
1754 void TMinuitPyCallback( void* vpyfunc, Long_t /* npar */,
1755 Int_t& a0, Double_t* a1, Double_t& a2, Double_t* a3, Int_t a4 ) {
1756 // a void* was passed to keep the interface on builtin types only
1757 PyObject* pyfunc = (PyObject*)vpyfunc;
1758
1759 // prepare arguments
1760 PyObject* pya0 = BufFac_t::Instance()->PyBuffer_FromMemory( &a0, sizeof(Int_t) );
1761 PyObject* pya1 = BufFac_t::Instance()->PyBuffer_FromMemory( a1, a0 * sizeof(Double_t) );
1762 PyObject* pya2 = BufFac_t::Instance()->PyBuffer_FromMemory( &a2, sizeof(Double_t) );
1763 PyObject* pya3 = BufFac_t::Instance()->PyBuffer_FromMemory( a3, -1 ); // size unknown
1764
1765 if ( ! (pya0 && pya1 && pya2 && pya3) ) {
1766 Py_XDECREF( pya3 ); Py_XDECREF( pya2 ); Py_XDECREF( pya1 ); Py_XDECREF( pya0 );
1767 return;
1768 }
1769
1770 // perform actual call
1771 PyObject* result = PyObject_CallFunction(
1772 pyfunc, (char*)"OOOOi", pya0, pya1, pya2, pya3, a4 );
1773 Py_DECREF( pya3 ); Py_DECREF( pya2 ); Py_DECREF( pya1 ); Py_DECREF( pya0 );
1774
1775 if ( ! result ) {
1776 PyErr_Print();
1777 throw std::runtime_error( "TMinuit python fit function call failed" );
1778 }
1779
1780 Py_XDECREF( result );
1781 }
1782
1783//- TFN behavior --------------------------------------------------------------
1784 double TFNPyCallback( void* vpyfunc, Long_t npar, double* a0, double* a1 ) {
1785 // a void* was passed to keep the interface on builtin types only
1786 PyObject* pyfunc = (PyObject*)vpyfunc;
1787
1788 // prepare arguments and call
1789 PyObject* pya0 = BufFac_t::Instance()->PyBuffer_FromMemory( a0, 4 * sizeof(double) );
1790 if ( ! pya0 )
1791 return 0.;
1792
1793 PyObject* result = 0;
1794 if ( npar != 0 ) {
1795 PyObject* pya1 = BufFac_t::Instance()->PyBuffer_FromMemory( a1, npar * sizeof(double) );
1796 result = PyObject_CallFunction( pyfunc, (char*)"OO", pya0, pya1 );
1797 Py_DECREF( pya1 );
1798 } else
1799 result = PyObject_CallFunction( pyfunc, (char*)"O", pya0 );
1800
1801 Py_DECREF( pya0 );
1802
1803 // translate result, throw if an error has occurred
1804 double d = 0.;
1805 if ( ! result ) {
1806 PyErr_Print();
1807 throw std::runtime_error( "TFN python function call failed" );
1808 } else {
1809 d = PyFloat_AsDouble( result );
1810 Py_DECREF( result );
1811 }
1812
1813 return d;
1814 }
1815
1816} // namespace PyROOT
1817
1818
1819namespace {
1820
1821// for convenience
1822 using namespace PyROOT;
1823
1824//- THN behavior --------------------------------------------------------------
1825 PyObject* THNIMul( PyObject* self, PyObject* scale )
1826 {
1827 // Use THN::Scale to perform *= ... need this stub to return self.
1828 PyObject* result = CallPyObjMethod( self, "Scale", scale );
1829 if ( ! result )
1830 return result;
1831
1832 Py_DECREF( result );
1833 Py_INCREF( self );
1834 return self;
1835 }
1836
1837
1838////////////////////////////////////////////////////////////////////////////////
1839
1840 class TPretendInterpreted: public PyCallable {
1841 public:
1842 TPretendInterpreted( int nArgs ) : fNArgs( nArgs ) {}
1843
1844 public:
1845 Int_t GetNArgs() { return fNArgs; }
1846 virtual Int_t GetPriority() { return 100; }
1847 virtual Int_t GetMaxArgs() { return GetNArgs()+1; }
1848 virtual PyObject* GetCoVarNames() {
1849 PyObject* co_varnames = PyTuple_New( 1 /* self */ + 1 /* fake */ );
1850 PyTuple_SET_ITEM( co_varnames, 0, PyROOT_PyUnicode_FromString( "self" ) );
1851 PyTuple_SET_ITEM( co_varnames, 1, PyROOT_PyUnicode_FromString( "*args" ) );
1852 return co_varnames;
1853 }
1854 virtual PyObject* GetArgDefault( Int_t ) { return NULL; }
1855
1856 Bool_t IsCallable( PyObject* pyobject )
1857 {
1858 // Determine whether the given pyobject is indeed callable.
1859 if ( ! pyobject || ! PyCallable_Check( pyobject ) ) {
1860 PyObject* str = pyobject ? PyObject_Str( pyobject ) : PyROOT_PyUnicode_FromString( "null pointer" );
1861 PyErr_Format( PyExc_ValueError,
1862 "\"%s\" is not a valid python callable", PyROOT_PyUnicode_AsString( str ) );
1863 Py_DECREF( str );
1864 return kFALSE;
1865 }
1866
1867 return kTRUE;
1868 }
1869
1870 private:
1871 Int_t fNArgs;
1872 };
1873
1874////////////////////////////////////////////////////////////////////////////////
1875
1876 class TF1InitWithPyFunc : public TPretendInterpreted {
1877 public:
1878 TF1InitWithPyFunc( int ntf = 1 ) : TPretendInterpreted( 2 + 2*ntf ) {}
1879
1880 public:
1881 virtual PyObject* GetSignature() { return PyROOT_PyUnicode_FromString( "(...)" ); }
1882 virtual PyObject* GetPrototype()
1883 {
1885 "TF1::TF1(const char* name, PyObject* callable, "
1886 "Double_t xmin, Double_t xmax, Int_t npar = 0)" );
1887 }
1888 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TF1" ); }
1889 virtual PyCallable* Clone() { return new TF1InitWithPyFunc( *this ); }
1890
1891 virtual PyObject* Call(
1892 ObjectProxy*& self, PyObject* args, PyObject* /* kwds */, TCallContext* /* ctxt */ )
1893 {
1894 // expected signature: ( char* name, pyfunc, double xmin, double xmax, int npar = 0 )
1895 int argc = PyTuple_GET_SIZE( args );
1896 const int reqNArgs = GetNArgs();
1897 if ( ! ( argc == reqNArgs || argc == reqNArgs+1 ) ) {
1898 PyErr_Format( PyExc_TypeError,
1899 "TFN::TFN(const char*, PyObject* callable, ...) =>\n"
1900 " takes at least %d and at most %d arguments (%d given)",
1901 reqNArgs, reqNArgs+1, argc );
1902 return 0; // reported as an overload failure
1903 }
1904
1905 PyObject* pyfunc = PyTuple_GET_ITEM( args, 1 );
1906
1907 // verify/setup the callback parameters
1908 Long_t npar = 0; // default value if not given
1909 if ( argc == reqNArgs+1 )
1910 npar = PyInt_AsLong( PyTuple_GET_ITEM( args, reqNArgs ) );
1911
1912 // create signature
1913 std::vector<std::string> signature; signature.reserve( 2 );
1914 signature.push_back( "double*" );
1915 signature.push_back( "double*" );
1916
1917 // registration with Cling
1918 void* fptr = Utility::CreateWrapperMethod(
1919 pyfunc, npar, "double", signature, "TFNPyCallback" );
1920 if ( ! fptr /* PyErr was set */ )
1921 return 0;
1922
1923 // get constructor
1924 MethodProxy* method =
1925 (MethodProxy*)PyObject_GetAttr( (PyObject*)self, PyStrings::gInit );
1926
1927 // build new argument array
1928 PyObject* newArgs = PyTuple_New( reqNArgs + 1 );
1929
1930 for ( int iarg = 0; iarg < argc; ++iarg ) {
1931 PyObject* item = PyTuple_GET_ITEM( args, iarg );
1932 if ( iarg != 1 ) {
1933 Py_INCREF( item );
1934 PyTuple_SET_ITEM( newArgs, iarg, item );
1935 } else {
1936 PyTuple_SET_ITEM( newArgs, iarg, PyROOT_PyCapsule_New( fptr, NULL, NULL ) );
1937 }
1938 }
1939
1940 if ( argc == reqNArgs ) // meaning: use default for last value
1941 PyTuple_SET_ITEM( newArgs, reqNArgs, PyInt_FromLong( 0l ) );
1942
1943 // re-run constructor, will select the proper one with void* for callback
1944 PyObject* result = PyObject_CallObject( (PyObject*)method, newArgs );
1945
1946 // done, may have worked, if not: 0 is returned
1947 Py_DECREF( newArgs );
1948 Py_DECREF( method );
1949 return result;
1950 }
1951 };
1952
1953////////////////////////////////////////////////////////////////////////////////
1954
1955 class TF2InitWithPyFunc : public TF1InitWithPyFunc {
1956 public:
1957 TF2InitWithPyFunc() : TF1InitWithPyFunc( 2 ) {}
1958
1959 public:
1960 virtual PyObject* GetPrototype()
1961 {
1963 "TF2::TF2(const char* name, PyObject* callable, "
1964 "Double_t xmin, Double_t xmax, "
1965 "Double_t ymin, Double_t ymax, Int_t npar = 0)" );
1966 }
1967 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TF2" ); }
1968 virtual PyCallable* Clone() { return new TF2InitWithPyFunc( *this ); }
1969 };
1970
1971////////////////////////////////////////////////////////////////////////////////
1972
1973 class TF3InitWithPyFunc : public TF1InitWithPyFunc {
1974 public:
1975 TF3InitWithPyFunc() : TF1InitWithPyFunc( 3 ) {}
1976
1977 public:
1978 virtual PyObject* GetPrototype()
1979 {
1981 "TF3::TF3(const char* name, PyObject* callable, "
1982 "Double_t xmin, Double_t xmax, "
1983 "Double_t ymin, Double_t ymax, "
1984 "Double_t zmin, Double_t zmax, Int_t npar = 0)" );
1985 }
1986 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TF3" ); }
1987 virtual PyCallable* Clone() { return new TF3InitWithPyFunc( *this ); }
1988 };
1989
1990//- TFunction behavior ---------------------------------------------------------
1991 PyObject* TFunctionCall( ObjectProxy*& self, PyObject* args ) {
1992 return TFunctionHolder( Cppyy::gGlobalScope, (Cppyy::TCppMethod_t)self->GetObject() ).Call( self, args, 0 );
1993 }
1994
1995
1996//- TMinuit behavior -----------------------------------------------------------
1997 class TMinuitSetFCN : public TPretendInterpreted {
1998 public:
1999 TMinuitSetFCN( int nArgs = 1 ) : TPretendInterpreted( nArgs ) {}
2000
2001 public:
2002 virtual PyObject* GetSignature() { return PyROOT_PyUnicode_FromString( "(PyObject* callable)" ); }
2003 virtual PyObject* GetPrototype()
2004 {
2006 "TMinuit::SetFCN(PyObject* callable)" );
2007 }
2008 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TMinuit" ); }
2009 virtual PyCallable* Clone() { return new TMinuitSetFCN( *this ); }
2010
2011 virtual PyObject* Call(
2012 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* ctxt )
2013 {
2014 // expected signature: ( pyfunc )
2015 int argc = PyTuple_GET_SIZE( args );
2016 if ( argc != 1 ) {
2017 PyErr_Format( PyExc_TypeError,
2018 "TMinuit::SetFCN(PyObject* callable, ...) =>\n"
2019 " takes exactly 1 argument (%d given)", argc );
2020 return 0; // reported as an overload failure
2021 }
2022
2023 PyObject* pyfunc = PyTuple_GET_ITEM( args, 0 );
2024 if ( ! IsCallable( pyfunc ) )
2025 return 0;
2026
2027 // create signature
2028 std::vector<std::string> signature; signature.reserve( 5 );
2029 signature.push_back( "Int_t&" );
2030 signature.push_back( "Double_t*" );
2031 signature.push_back( "Double_t&" );
2032 signature.push_back( "Double_t*" );
2033 signature.push_back( "Int_t" );
2034
2035 // registration with Cling
2036 void* fptr = Utility::CreateWrapperMethod(
2037 pyfunc, 5, "void", signature, "TMinuitPyCallback" );
2038 if ( ! fptr /* PyErr was set */ )
2039 return 0;
2040
2041 // get setter function
2042 MethodProxy* method =
2043 (MethodProxy*)PyObject_GetAttr( (PyObject*)self, PyStrings::gSetFCN );
2044
2045 // CLING WORKAROUND: SetFCN(void* fun) is deprecated but for whatever reason
2046 // still available yet not functional; select the correct one based on its
2047 // signature of the full function pointer
2048 PyCallable* setFCN = 0;
2049 const MethodProxy::Methods_t& methods = method->fMethodInfo->fMethods;
2050 for ( MethodProxy::Methods_t::const_iterator im = methods.begin(); im != methods.end(); ++im ) {
2051 PyObject* sig = (*im)->GetSignature();
2052 if ( sig && strstr( PyROOT_PyUnicode_AsString( sig ), "Double_t&" ) ) {
2053 // the comparison was not exact, but this is just a workaround
2054 setFCN = *im;
2055 Py_DECREF( sig );
2056 break;
2057 }
2058 Py_DECREF( sig );
2059 }
2060 if ( ! setFCN ) // this never happens but Coverity insists; it can be
2061 return 0; // removed with the workaround in due time
2062 // END CLING WORKAROUND
2063
2064 // build new argument array
2065 PyObject* newArgs = PyTuple_New( 1 );
2066 PyTuple_SET_ITEM( newArgs, 0, PyROOT_PyCapsule_New( fptr, NULL, NULL ) );
2067
2068 // re-run
2069 // CLING WORKAROUND: this is to be the call once TMinuit is fixed:
2070 // PyObject* result = PyObject_CallObject( (PyObject*)method, newArgs );
2071 PyObject* result = setFCN->Call( self, newArgs, kwds, ctxt );
2072 // END CLING WORKAROUND
2073
2074 // done, may have worked, if not: 0 is returned
2075 Py_DECREF( newArgs );
2076 Py_DECREF( method );
2077 return result;
2078 }
2079 };
2080
2081 class TMinuitFitterSetFCN : public TMinuitSetFCN {
2082 public:
2083 TMinuitFitterSetFCN() : TMinuitSetFCN( 1 ) {}
2084
2085 public:
2086 virtual PyObject* GetPrototype()
2087 {
2089 "TMinuitFitter::SetFCN(PyObject* callable)" );
2090 }
2091
2092 virtual PyCallable* Clone() { return new TMinuitFitterSetFCN( *this ); }
2093
2094 virtual PyObject* Call(
2095 ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* ctxt )
2096 {
2097 // expected signature: ( pyfunc )
2098 int argc = PyTuple_GET_SIZE( args );
2099 if ( argc != 1 ) {
2100 PyErr_Format( PyExc_TypeError,
2101 "TMinuitFitter::SetFCN(PyObject* callable, ...) =>\n"
2102 " takes exactly 1 argument (%d given)", argc );
2103 return 0; // reported as an overload failure
2104 }
2105
2106 return TMinuitSetFCN::Call( self, args, kwds, ctxt );
2107 }
2108 };
2109
2110//- Fit::TFitter behavior ------------------------------------------------------
2111 PyObject* gFitterPyCallback = 0;
2112
2113 void FitterPyCallback( int& npar, double* gin, double& f, double* u, int flag )
2114 {
2115 // Cling-callable callback for Fit::Fitter derived objects.
2116 PyObject* result = 0;
2117
2118 // prepare arguments
2119 PyObject* arg1 = BufFac_t::Instance()->PyBuffer_FromMemory( &npar );
2120
2121 PyObject* arg2 = BufFac_t::Instance()->PyBuffer_FromMemory( gin );
2122
2123 PyObject* arg3 = PyList_New( 1 );
2124 PyList_SetItem( arg3, 0, PyFloat_FromDouble( f ) );
2125
2126 PyObject* arg4 = BufFac_t::Instance()->PyBuffer_FromMemory( u, npar * sizeof(double) );
2127
2128 // perform actual call
2129 result = PyObject_CallFunction(
2130 gFitterPyCallback, (char*)"OOOOi", arg1, arg2, arg3, arg4, flag );
2131 f = PyFloat_AsDouble( PyList_GetItem( arg3, 0 ) );
2132
2133 Py_DECREF( arg4 ); Py_DECREF( arg3 ); Py_DECREF( arg2 ); Py_DECREF( arg1 );
2134
2135 if ( ! result ) {
2136 PyErr_Print();
2137 throw std::runtime_error( "TMinuit python fit function call failed" );
2138 }
2139
2140 Py_XDECREF( result );
2141 }
2142
2143 class TFitterFitFCN : public TPretendInterpreted {
2144 public:
2145 TFitterFitFCN() : TPretendInterpreted( 2 ) {}
2146
2147 public:
2148 virtual PyObject* GetSignature()
2149 {
2151 "(PyObject* callable, int npar = 0, const double* params = 0, unsigned int dataSize = 0, bool chi2fit = false)" );
2152 }
2153 virtual PyObject* GetPrototype()
2154 {
2156 "TFitter::FitFCN(PyObject* callable, int npar = 0, const double* params = 0, unsigned int dataSize = 0, bool chi2fit = false)" );
2157 }
2158 virtual PyObject* GetScopeProxy() { return CreateScopeProxy( "TFitter" ); }
2159 virtual PyCallable* Clone() { return new TFitterFitFCN( *this ); }
2160
2161 virtual PyObject* Call(
2162 ObjectProxy*& self, PyObject* args, PyObject* /* kwds */, TCallContext* /* ctxt */ )
2163 {
2164 // expected signature: ( self, pyfunc, int npar = 0, const double* params = 0, unsigned int dataSize = 0, bool chi2fit = false )
2165 int argc = PyTuple_GET_SIZE( args );
2166 if ( argc < 1 ) {
2167 PyErr_Format( PyExc_TypeError,
2168 "TFitter::FitFCN(PyObject* callable, ...) =>\n"
2169 " takes at least 1 argument (%d given)", argc );
2170 return 0; // reported as an overload failure
2171 }
2172
2173 PyObject* pyfunc = PyTuple_GET_ITEM( args, 0 );
2174 if ( ! IsCallable( pyfunc ) )
2175 return 0;
2176
2177 // global registration
2178 Py_XDECREF( gFitterPyCallback );
2179 Py_INCREF( pyfunc );
2180 gFitterPyCallback = pyfunc;
2181
2182 // get function
2183 MethodProxy* method =
2184 (MethodProxy*)PyObject_GetAttr( (PyObject*)self, PyStrings::gFitFCN );
2185
2186 // build new argument array
2187 PyObject* newArgs = PyTuple_New( argc );
2188 PyTuple_SET_ITEM( newArgs, 0, PyROOT_PyCapsule_New( (void*)FitterPyCallback, NULL, NULL ) );
2189 for ( int iarg = 1; iarg < argc; ++iarg ) {
2190 PyObject* pyarg = PyTuple_GET_ITEM( args, iarg );
2191 Py_INCREF( pyarg );
2192 PyTuple_SET_ITEM( newArgs, iarg, pyarg );
2193 }
2194
2195 // re-run
2196 PyObject* result = PyObject_CallObject( (PyObject*)method, newArgs );
2197
2198 // done, may have worked, if not: 0 is returned
2199 Py_DECREF( newArgs );
2200 Py_DECREF( method );
2201 return result;
2202 }
2203 };
2204
2205
2206//- TFile::Get -----------------------------------------------------------------
2207 PyObject* TFileGetAttr( PyObject* self, PyObject* attr )
2208 {
2209 // Pythonization of TFile::Get that raises AttributeError on failure.
2210 PyObject* result = CallPyObjMethod( self, "Get", attr );
2211 if ( !result )
2212 return result;
2213
2214 if ( !PyObject_IsTrue( result ) ) {
2215 PyObject* astr = PyObject_Str( attr );
2216 PyErr_Format( PyExc_AttributeError, "TFile object has no attribute \'%s\'",
2217 PyROOT_PyUnicode_AsString( astr ) );
2218 Py_DECREF( astr );
2219 Py_DECREF( result );
2220 return nullptr;
2221 }
2222
2223 // caching behavior seems to be more clear to the user; can always override said
2224 // behavior (i.e. re-read from file) with an explicit Get() call
2225 PyObject_SetAttr( self, attr, result );
2226 return result;
2227 }
2228
2229// This is done for TFile, but Get() is really defined in TDirectoryFile and its base
2230// TDirectory suffers from a similar problem. Nevertheless, the TFile case is by far
2231// the most common, so we'll leave it at this until someone asks for one of the bases
2232// to be pythonized.
2233 PyObject* TDirectoryFileGet( ObjectProxy* self, PyObject* pynamecycle )
2234 {
2235 // Pythonization of TDirectoryFile::Get that handles non-TObject deriveds
2236 if ( ! ObjectProxy_Check( self ) ) {
2237 PyErr_SetString( PyExc_TypeError,
2238 "TDirectoryFile::Get must be called with a TDirectoryFile instance as first argument" );
2239 return nullptr;
2240 }
2241
2242 TDirectoryFile* dirf =
2244 if ( !dirf ) {
2245 PyErr_SetString( PyExc_ReferenceError, "attempt to access a null-pointer" );
2246 return nullptr;
2247 }
2248
2249 const char* namecycle = PyROOT_PyUnicode_AsString( pynamecycle );
2250 if ( !namecycle )
2251 return nullptr; // TypeError already set
2252
2253 TKey* key = dirf->GetKey( namecycle );
2254 if ( key ) {
2255 void* addr = dirf->GetObjectChecked( namecycle, key->GetClassName() );
2256 return BindCppObjectNoCast( addr,
2258 }
2259
2260 // no key? for better or worse, call normal Get()
2261 void* addr = dirf->Get( namecycle );
2262 return BindCppObject( addr, (Cppyy::TCppType_t)Cppyy::GetScope( "TObject" ), kFALSE );
2263 }
2264
2265 //- Pretty printing with cling::PrintValue
2266 PyObject *ClingPrintValue(ObjectProxy *self)
2267 {
2268 PyObject *cppname = PyObject_GetAttrString((PyObject *)self, "__cppname__");
2269 if (!PyROOT_PyUnicode_Check(cppname))
2270 return 0;
2271 std::string className = PyROOT_PyUnicode_AsString(cppname);
2272 Py_XDECREF(cppname);
2273
2274 std::string printResult = gInterpreter->ToString(className.c_str(), self->GetObject());
2275 if (printResult.find("@0x") == 0) {
2276 // Fall back to __repr__ if we just get an address from cling
2277 auto method = PyObject_GetAttrString((PyObject*)self, "__repr__");
2278 auto res = PyObject_CallObject(method, nullptr);
2279 Py_DECREF(method);
2280 return res;
2281 } else {
2282 return PyROOT_PyUnicode_FromString(printResult.c_str());
2283 }
2284 }
2285
2286 //- Adding array interface to classes ---------------
2287 void AddArrayInterface(PyObject *pyclass, PyCFunction func)
2288 {
2289 Utility::AddToClass(pyclass, "_get__array_interface__", func, METH_NOARGS);
2290 }
2291
2292 template <typename dtype>
2293 PyObject *FillArrayInterfaceDict(char type)
2294 {
2295 PyObject *dict = PyDict_New();
2296 PyDict_SetItemString(dict, "version", PyLong_FromLong(3));
2297#ifdef R__BYTESWAP
2298 const char endianess = '<';
2299#else
2300 const char endianess = '>';
2301#endif
2302 const UInt_t bytes = sizeof(dtype);
2303 PyDict_SetItemString(dict, "typestr",
2304 PyROOT_PyUnicode_FromString(TString::Format("%c%c%i", endianess, type, bytes).Data()));
2305 return dict;
2306 }
2307
2308 template <typename dtype, char typestr>
2309 PyObject *STLVectorArrayInterface(ObjectProxy *self)
2310 {
2311 std::vector<dtype> *cobj = (std::vector<dtype> *)(self->GetObject());
2312
2313 PyObject *dict = FillArrayInterfaceDict<dtype>(typestr);
2314 PyDict_SetItemString(dict, "shape", PyTuple_Pack(1, PyLong_FromLong(cobj->size())));
2315 PyDict_SetItemString(dict, "data",
2316 PyTuple_Pack(2, PyLong_FromLong(reinterpret_cast<long>(cobj->data())), Py_False));
2317
2318 return dict;
2319 }
2320
2321 template <typename dtype, char typestr>
2322 PyObject *RVecArrayInterface(ObjectProxy *self)
2323 {
2324 using ROOT::VecOps::RVec;
2325 RVec<dtype> *cobj = (RVec<dtype> *)(self->GetObject());
2326
2327 PyObject *dict = FillArrayInterfaceDict<dtype>(typestr);
2328 PyDict_SetItemString(dict, "shape", PyTuple_Pack(1, PyLong_FromLong(cobj->size())));
2329 PyDict_SetItemString(dict, "data",
2330 PyTuple_Pack(2, PyLong_FromLong(reinterpret_cast<long>(cobj->data())), Py_False));
2331
2332 return dict;
2333 }
2334
2335 //- simplistic len() functions -------------------------------------------------
2336 PyObject* ReturnThree( ObjectProxy*, PyObject* ) {
2337 return PyInt_FromLong( 3 );
2338 }
2339
2340 PyObject* ReturnTwo( ObjectProxy*, PyObject* ) {
2341 return PyInt_FromLong( 2 );
2342 }
2343
2344} // unnamed namespace
2345
2346
2347//- public functions -----------------------------------------------------------
2348Bool_t PyROOT::Pythonize( PyObject* pyclass, const std::string& name )
2349{
2350// Add pre-defined pythonizations (for STL and ROOT) to classes based on their
2351// signature and/or class name.
2352 if ( pyclass == 0 )
2353 return kFALSE;
2354
2355 // add pretty printing
2356 Utility::AddToClass(pyclass, "__str__", (PyCFunction)ClingPrintValue);
2357
2358 //- method name based pythonization --------------------------------------------
2359
2360 // for smart pointer style classes (note fall-through)
2361 if ( HasAttrDirect( pyclass, PyStrings::gDeref ) ) {
2362 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) DeRefGetAttr, METH_O );
2363 } else if ( HasAttrDirect( pyclass, PyStrings::gFollow ) ) {
2364 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) FollowGetAttr, METH_O );
2365 }
2366
2367// for STL containers, and user classes modeled after them
2368 if ( HasAttrDirect( pyclass, PyStrings::gSize ) )
2369 Utility::AddToClass( pyclass, "__len__", "size" );
2370
2371// like-wise, some typical container sizings
2372 if ( HasAttrDirect( pyclass, PyStrings::gGetSize ) )
2373 Utility::AddToClass( pyclass, "__len__", "GetSize" );
2374
2375 if ( HasAttrDirect( pyclass, PyStrings::ggetSize ) )
2376 Utility::AddToClass( pyclass, "__len__", "getSize" );
2377
2378 if ( HasAttrDirect( pyclass, PyStrings::gBegin ) && HasAttrDirect( pyclass, PyStrings::gEnd ) ) {
2379 // some classes may not have dicts for their iterators, making begin/end useless
2380 PyObject* pyfullname = PyObject_GetAttr( pyclass, PyStrings::gCppName );
2381 if ( ! pyfullname ) pyfullname = PyObject_GetAttr( pyclass, PyStrings::gName );
2382 TClass* klass = TClass::GetClass( PyROOT_PyUnicode_AsString( pyfullname ) );
2383 Py_DECREF( pyfullname );
2384
2385 if (!klass->InheritsFrom(TCollection::Class())) {
2386 // TCollection has a begin and end method so that they can be used in
2387 // the C++ range expression. However, unlike any other use of TIter,
2388 // TCollection::begin must include the first iteration. PyROOT is
2389 // handling TIter as a special case (as it should) and also does this
2390 // first iteration (via the first call to Next to get the first element)
2391 // and thus using begin in this case lead to the first element being
2392 // forgotten by PyROOT.
2393 // i.e. Don't search for begin in TCollection since we can not use.'
2394
2395 TMethod* meth = klass->GetMethodAllAny( "begin" );
2396
2397 TClass* iklass = 0;
2398 if ( meth ) {
2400 iklass = TClass::GetClass( meth->GetReturnTypeNormalizedName().c_str() );
2401 gErrorIgnoreLevel = oldl;
2402 }
2403
2404 if ( iklass && iklass->GetClassInfo() ) {
2405 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)StlSequenceIter;
2406 Utility::AddToClass( pyclass, "__iter__", (PyCFunction) StlSequenceIter, METH_NOARGS );
2407 } else if ( HasAttrDirect( pyclass, PyStrings::gGetItem ) && HasAttrDirect( pyclass, PyStrings::gLen ) ) {
2408 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2409 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2410 }
2411 }
2412 }
2413
2414// search for global comparator overloads (may fail; not sure whether it isn't better to
2415// do this lazily just as is done for math operators, but this interplays nicely with the
2416// generic versions)
2417 Utility::AddBinaryOperator( pyclass, "==", "__eq__" );
2418 Utility::AddBinaryOperator( pyclass, "!=", "__ne__" );
2419
2420// map operator==() through GenObjectIsEqual to allow comparison to None (kTRUE is to
2421// require that the located method is a MethodProxy; this prevents circular calls as
2422// GenObjectIsEqual is no MethodProxy)
2423 if ( HasAttrDirect( pyclass, PyStrings::gEq, kTRUE ) ) {
2424 Utility::AddToClass( pyclass, "__cpp_eq__", "__eq__" );
2425 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) GenObjectIsEqual, METH_O );
2426 }
2427
2428// map operator!=() through GenObjectIsNotEqual to allow comparison to None (see note
2429// on kTRUE above for __eq__)
2430 if ( HasAttrDirect( pyclass, PyStrings::gNe, kTRUE ) ) {
2431 Utility::AddToClass( pyclass, "__cpp_ne__", "__ne__" );
2432 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) GenObjectIsNotEqual, METH_O );
2433 }
2434
2435
2436//- class name based pythonization ---------------------------------------------
2437
2438 if ( name == "TObject" ) {
2439 // support for the 'in' operator
2440 Utility::AddToClass( pyclass, "__contains__", (PyCFunction) TObjectContains, METH_O );
2441
2442 // comparing for lists
2443 Utility::AddToClass( pyclass, "__cmp__", (PyCFunction) TObjectCompare, METH_O );
2444 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) TObjectIsEqual, METH_O );
2445 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) TObjectIsNotEqual, METH_O );
2446
2447 }
2448
2449 else if ( name == "TClass" ) {
2450 // make DynamicCast return a usable python object, rather than void*
2451 Utility::AddToClass( pyclass, "_TClass__DynamicCast", "DynamicCast" );
2452 Utility::AddToClass( pyclass, "DynamicCast", (PyCFunction) TClassDynamicCast );
2453
2454 // the following cast is easier to use (reads both ways)
2455 Utility::AddToClass( pyclass, "StaticCast", (PyCFunction) TClassStaticCast );
2456
2457 }
2458
2459 else if ( name == "TCollection" ) {
2460 Utility::AddToClass( pyclass, "append", "Add" );
2461 Utility::AddToClass( pyclass, "extend", (PyCFunction) TCollectionExtend, METH_O );
2462 Utility::AddToClass( pyclass, "remove", (PyCFunction) TCollectionRemove, METH_O );
2463 Utility::AddToClass( pyclass, "__add__", (PyCFunction) TCollectionAdd, METH_O );
2464 Utility::AddToClass( pyclass, "__imul__", (PyCFunction) TCollectionIMul, METH_O );
2465 Utility::AddToClass( pyclass, "__mul__", (PyCFunction) TCollectionMul, METH_O );
2466 Utility::AddToClass( pyclass, "__rmul__", (PyCFunction) TCollectionMul, METH_O );
2467
2468 Utility::AddToClass( pyclass, "count", (PyCFunction) TCollectionCount, METH_O );
2469
2470 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)TCollectionIter;
2471 Utility::AddToClass( pyclass, "__iter__", (PyCFunction)TCollectionIter, METH_NOARGS );
2472
2473 }
2474
2475 else if ( name == "TSeqCollection" ) {
2476 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) TSeqCollectionGetItem, METH_O );
2477 Utility::AddToClass( pyclass, "__setitem__", (PyCFunction) TSeqCollectionSetItem );
2478 Utility::AddToClass( pyclass, "__delitem__", (PyCFunction) TSeqCollectionDelItem, METH_O );
2479
2480 Utility::AddToClass( pyclass, "insert", (PyCFunction) TSeqCollectionInsert );
2481 Utility::AddToClass( pyclass, "pop", (PyCFunction) TSeqCollectionPop );
2482 Utility::AddToClass( pyclass, "reverse", (PyCFunction) TSeqCollectionReverse, METH_NOARGS );
2483 Utility::AddToClass( pyclass, "sort", (PyCFunction) TSeqCollectionSort,
2484 METH_VARARGS | METH_KEYWORDS );
2485
2486 Utility::AddToClass( pyclass, "index", (PyCFunction) TSeqCollectionIndex, METH_O );
2487
2488 }
2489
2490 else if ( name == "TObjArray" ) {
2491 Utility::AddToClass( pyclass, "__len__", (PyCFunction) TObjArrayLen, METH_NOARGS );
2492 }
2493
2494 else if ( name == "TClonesArray" ) {
2495 // restore base TSeqCollection operator[] to prevent random object creation (it's
2496 // functionality is equivalent to the operator[](int) const of TClonesArray, but
2497 // there's no guarantee it'll be selected over the non-const version)
2498 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) TSeqCollectionGetItem, METH_O );
2499
2500 // this setitem should be used with as much care as the C++ one
2501 Utility::AddToClass( pyclass, "__setitem__", (PyCFunction) TClonesArraySetItem );
2502
2503 }
2504
2505 else if ( IsTemplatedSTLClass( name, "vector" ) || (name.find("ROOT::VecOps::RVec<") == 0) ) {
2506
2507 if ( HasAttrDirect( pyclass, PyStrings::gLen ) && HasAttrDirect( pyclass, PyStrings::gAt ) ) {
2508 Utility::AddToClass( pyclass, "_vector__at", "at" );
2509 // remove iterator that was set earlier (checked __getitem__ will do the trick)
2510 if ( HasAttrDirect( pyclass, PyStrings::gIter ) )
2511 PyObject_DelAttr( pyclass, PyStrings::gIter );
2512 } else if ( HasAttrDirect( pyclass, PyStrings::gGetItem ) ) {
2513 Utility::AddToClass( pyclass, "_vector__at", "__getitem__" ); // unchecked!
2514 }
2515
2516 // vector-optimized iterator protocol
2517 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)vector_iter;
2518
2519 // helpers for iteration
2520 TypedefInfo_t* ti = gInterpreter->TypedefInfo_Factory( (name+"::value_type").c_str() );
2521 if ( gInterpreter->TypedefInfo_IsValid( ti ) ) {
2522 PyObject* pyvalue_size = PyLong_FromLong( gInterpreter->TypedefInfo_Size( ti ) );
2523 PyObject_SetAttrString( pyclass, "value_size", pyvalue_size );
2524 Py_DECREF( pyvalue_size );
2525
2526 PyObject* pyvalue_type = PyROOT_PyUnicode_FromString( gInterpreter->TypedefInfo_TrueName( ti ) );
2527 PyObject_SetAttrString( pyclass, "value_type", pyvalue_type );
2528 Py_DECREF( pyvalue_type );
2529 }
2530 gInterpreter->TypedefInfo_Delete( ti );
2531
2532 // provide a slice-able __getitem__, if possible
2533 if ( HasAttrDirect( pyclass, PyStrings::gVectorAt ) )
2534 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) VectorGetItem, METH_O );
2535
2536 // std::vector<bool> is a special case in C++
2537 std::string::size_type pos = name.find( "vector<bool" ); // to cover all variations
2538 if ( pos == 0 /* at beginning */ || pos == 5 /* after std:: */ ) {
2539 Utility::AddToClass( pyclass, "__setitem__", (PyCFunction) VectorBoolSetItem );
2540 }
2541
2542 // add array interface for STL vectors
2543 if (name.find("ROOT::VecOps::RVec<") == 0) {
2544 } else if (name == "vector<float>") {
2545 AddArrayInterface(pyclass, (PyCFunction)STLVectorArrayInterface<float, 'f'>);
2546 } else if (name == "vector<double>") {
2547 AddArrayInterface(pyclass, (PyCFunction)STLVectorArrayInterface<double, 'f'>);
2548 } else if (name == "vector<int>") {
2549 AddArrayInterface(pyclass, (PyCFunction)STLVectorArrayInterface<int, 'i'>);
2550 } else if (name == "vector<unsigned int>") {
2551 AddArrayInterface(pyclass, (PyCFunction)STLVectorArrayInterface<unsigned int, 'u'>);
2552 } else if (name == "vector<long>") {
2553 AddArrayInterface(pyclass, (PyCFunction)STLVectorArrayInterface<long, 'i'>);
2554 } else if (name == "vector<unsigned long>") {
2555 AddArrayInterface(pyclass, (PyCFunction)STLVectorArrayInterface<unsigned long, 'u'>);
2556 }
2557
2558 // add array interface for RVecs
2559 if (name.find("ROOT::VecOps::RVec<") != 0) {
2560 } else if (name == "ROOT::VecOps::RVec<float>") {
2561 AddArrayInterface(pyclass, (PyCFunction)RVecArrayInterface<float, 'f'>);
2562 } else if (name == "ROOT::VecOps::RVec<double>") {
2563 AddArrayInterface(pyclass, (PyCFunction)RVecArrayInterface<double, 'f'>);
2564 } else if (name == "ROOT::VecOps::RVec<int>") {
2565 AddArrayInterface(pyclass, (PyCFunction)RVecArrayInterface<int, 'i'>);
2566 } else if (name == "ROOT::VecOps::RVec<unsigned int>") {
2567 AddArrayInterface(pyclass, (PyCFunction)RVecArrayInterface<unsigned int, 'u'>);
2568 } else if (name == "ROOT::VecOps::RVec<long>") {
2569 AddArrayInterface(pyclass, (PyCFunction)RVecArrayInterface<long, 'i'>);
2570 } else if (name == "ROOT::VecOps::RVec<unsigned long>") {
2571 AddArrayInterface(pyclass, (PyCFunction)RVecArrayInterface<unsigned long, 'u'>);
2572 }
2573 }
2574
2575 else if ( IsTemplatedSTLClass( name, "map" ) ) {
2576 Utility::AddToClass( pyclass, "__contains__", (PyCFunction) MapContains, METH_O );
2577
2578 }
2579
2580 else if ( IsTemplatedSTLClass( name, "pair" ) ) {
2581 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) PairUnpack, METH_O );
2582 Utility::AddToClass( pyclass, "__len__", (PyCFunction) ReturnTwo, METH_NOARGS );
2583
2584 }
2585
2586 else if ( name.find( "iterator" ) != std::string::npos ) {
2587 ((PyTypeObject*)pyclass)->tp_iternext = (iternextfunc)StlIterNext;
2588 Utility::AddToClass( pyclass, PYROOT__next__, (PyCFunction) StlIterNext, METH_NOARGS );
2589
2590 // special case, if operator== is a global overload and included in the dictionary
2591 if ( ! HasAttrDirect( pyclass, PyStrings::gCppEq, kTRUE ) )
2592 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) StlIterIsEqual, METH_O );
2593 if ( ! HasAttrDirect( pyclass, PyStrings::gCppNe, kTRUE ) )
2594 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) StlIterIsNotEqual, METH_O );
2595
2596 }
2597
2598 else if ( name == "string" || name == "std::string" ) {
2599 Utility::AddToClass( pyclass, "__repr__", (PyCFunction) StlStringRepr, METH_NOARGS );
2600 Utility::AddToClass( pyclass, "__str__", "c_str" );
2601 Utility::AddToClass( pyclass, "__cmp__", (PyCFunction) StlStringCompare, METH_O );
2602 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) StlStringIsEqual, METH_O );
2603 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) StlStringIsNotEqual, METH_O );
2604
2605 }
2606
2607 else if ( name == "TString" ) {
2608 Utility::AddToClass( pyclass, "__repr__", (PyCFunction) TStringRepr, METH_NOARGS );
2609 Utility::AddToClass( pyclass, "__str__", "Data" );
2610 Utility::AddToClass( pyclass, "__len__", "Length" );
2611
2612 Utility::AddToClass( pyclass, "__cmp__", "CompareTo" );
2613 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) TStringIsEqual, METH_O );
2614 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) TStringIsNotEqual, METH_O );
2615
2616 }
2617
2618 else if ( name == "TObjString" ) {
2619 Utility::AddToClass( pyclass, "__repr__", (PyCFunction) TObjStringRepr, METH_NOARGS );
2620 Utility::AddToClass( pyclass, "__str__", "GetName" );
2621 Utility::AddToClass( pyclass, "__len__", (PyCFunction) TObjStringLength, METH_NOARGS );
2622
2623 Utility::AddToClass( pyclass, "__cmp__", (PyCFunction) TObjStringCompare, METH_O );
2624 Utility::AddToClass( pyclass, "__eq__", (PyCFunction) TObjStringIsEqual, METH_O );
2625 Utility::AddToClass( pyclass, "__ne__", (PyCFunction) TObjStringIsNotEqual, METH_O );
2626
2627 }
2628
2629 else if ( name == "TIter" ) {
2630 ((PyTypeObject*)pyclass)->tp_iter = (getiterfunc)PyObject_SelfIter;
2631 Utility::AddToClass( pyclass, "__iter__", (PyCFunction) PyObject_SelfIter, METH_NOARGS );
2632
2633 ((PyTypeObject*)pyclass)->tp_iternext = (iternextfunc)TIterNext;
2634 Utility::AddToClass( pyclass, PYROOT__next__, (PyCFunction) TIterNext, METH_NOARGS );
2635
2636 }
2637
2638 else if ( name == "TDirectory" ) {
2639 // note: this replaces the already existing TDirectory::GetObject()
2640 Utility::AddToClass( pyclass, "GetObject", (PyCFunction) TDirectoryGetObject );
2641
2642 // note: this replaces the already existing TDirectory::WriteObject()
2643 Utility::AddToClass( pyclass, "WriteObject", (PyCFunction) TDirectoryWriteObject );
2644
2645 }
2646
2647 else if ( name == "TDirectoryFile" ) {
2648 // add safety for non-TObject derived Get() results
2649 Utility::AddToClass( pyclass, "Get", (PyCFunction) TDirectoryFileGet, METH_O );
2650
2651 return kTRUE;
2652 }
2653
2654 else if ( name == "TTree" ) {
2655 // allow direct browsing of the tree
2656 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) TTreeGetAttr, METH_O );
2657
2658 // workaround for templated member Branch()
2659 MethodProxy* original =
2660 (MethodProxy*)PyObject_GetAttrFromDict( pyclass, PyStrings::gBranch );
2661 MethodProxy* method = MethodProxy_New( "Branch", new TTreeBranch( original ) );
2662 Py_DECREF( original ); original = 0;
2663
2664 PyObject_SetAttrString(
2665 pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
2666 Py_DECREF( method ); method = 0;
2667
2668 // workaround for templated member SetBranchAddress()
2669 original = (MethodProxy*)PyObject_GetAttrFromDict( pyclass, PyStrings::gSetBranchAddress );
2670 method = MethodProxy_New( "SetBranchAddress", new TTreeSetBranchAddress( original ) );
2671 Py_DECREF( original ); original = 0;
2672
2673 PyObject_SetAttrString(
2674 pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
2675 Py_DECREF( method ); method = 0;
2676
2677 }
2678
2679 else if ( name == "TChain" ) {
2680 // allow SetBranchAddress to take object directly, w/o needing AddressOf()
2681 MethodProxy* original =
2682 (MethodProxy*)PyObject_GetAttrFromDict( pyclass, PyStrings::gSetBranchAddress );
2683 MethodProxy* method = MethodProxy_New( "SetBranchAddress", new TChainSetBranchAddress( original ) );
2684 Py_DECREF( original ); original = 0;
2685
2686 PyObject_SetAttrString(
2687 pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
2688 Py_DECREF( method ); method = 0;
2689
2690 }
2691
2692 else if ( name == "TStyle" ) {
2693 MethodProxy* ctor = (MethodProxy*)PyObject_GetAttr( pyclass, PyStrings::gInit );
2694 ctor->fMethodInfo->fFlags &= ~TCallContext::kIsCreator;
2695 Py_DECREF( ctor );
2696 }
2697
2698 else if ( name == "TH1" ) // allow hist *= scalar
2699 Utility::AddToClass( pyclass, "__imul__", (PyCFunction) THNIMul, METH_O );
2700
2701 else if ( name == "TF1" ) // allow instantiation with python callable
2702 Utility::AddToClass( pyclass, "__init__", new TF1InitWithPyFunc );
2703
2704 else if ( name == "TF2" ) // allow instantiation with python callable
2705 Utility::AddToClass( pyclass, "__init__", new TF2InitWithPyFunc );
2706
2707 else if ( name == "TF3" ) // allow instantiation with python callable
2708 Utility::AddToClass( pyclass, "__init__", new TF3InitWithPyFunc );
2709
2710 else if ( name == "TFunction" ) // allow direct call
2711 Utility::AddToClass( pyclass, "__call__", (PyCFunction) TFunctionCall );
2712
2713 else if ( name == "TMinuit" ) // allow call with python callable
2714 Utility::AddToClass( pyclass, "SetFCN", new TMinuitSetFCN );
2715
2716 else if ( name == "TFitter" ) // allow call with python callable (this is not correct)
2717 Utility::AddToClass( pyclass, "SetFCN", new TMinuitFitterSetFCN );
2718
2719 else if ( name == "Fitter" ) // really Fit::Fitter, allow call with python callable
2720 Utility::AddToClass( pyclass, "FitFCN", new TFitterFitFCN );
2721
2722 else if ( name == "TFile" ) {
2723 // TFile::Open really is a constructor, really
2724 PyObject* attr = PyObject_GetAttrString( pyclass, (char*)"Open" );
2725 if ( MethodProxy_Check( attr ) )
2726 ((MethodProxy*)attr)->fMethodInfo->fFlags |= TCallContext::kIsCreator;
2727 Py_XDECREF( attr );
2728
2729 // allow member-style access to entries in file
2730 Utility::AddToClass( pyclass, "__getattr__", (PyCFunction) TFileGetAttr, METH_O );
2731
2732 }
2733
2734 else if ( name.substr(0,8) == "TVector3" ) {
2735 Utility::AddToClass( pyclass, "__len__", (PyCFunction) ReturnThree, METH_NOARGS );
2736 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2737 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2738
2739 }
2740
2741 else if ( name.substr(0,8) == "TVectorT" ) {
2742 // allow proper iteration
2743 Utility::AddToClass( pyclass, "__len__", "GetNoElements" );
2744 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2745 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2746 }
2747
2748 else if ( name.substr(0,6) == "TArray" && name != "TArray" ) { // allow proper iteration
2749 // __len__ is already set from GetSize()
2750 Utility::AddToClass( pyclass, "_getitem__unchecked", "__getitem__" );
2751 Utility::AddToClass( pyclass, "__getitem__", (PyCFunction) CheckedGetItem, METH_O );
2752 }
2753
2754// Make RooFit 'using' member functions available (not supported by dictionary)
2755 else if ( name == "RooDataHist" )
2756 Utility::AddUsingToClass( pyclass, "plotOn" );
2757
2758 else if ( name == "RooSimultaneous" )
2759 Utility::AddUsingToClass( pyclass, "plotOn" );
2760
2761 // TODO: store these on the pythonizations module, not on gRootModule
2762 // TODO: externalize this code and use update handlers on the python side
2763 PyObject* userPythonizations = PyObject_GetAttrString( gRootModule, "UserPythonizations" );
2764 PyObject* pythonizationScope = PyObject_GetAttrString( gRootModule, "PythonizationScope" );
2765
2766 std::vector< std::string > pythonization_scopes;
2767 pythonization_scopes.push_back( "__global__" );
2768
2769 std::string user_scope = PyROOT_PyUnicode_AsString( pythonizationScope );
2770 if ( user_scope != "__global__" ) {
2771 if ( PyDict_Contains( userPythonizations, pythonizationScope ) ) {
2772 pythonization_scopes.push_back( user_scope );
2773 }
2774 }
2775
2776 Bool_t pstatus = kTRUE;
2777
2778 for ( auto key = pythonization_scopes.cbegin(); key != pythonization_scopes.cend(); ++key ) {
2779 PyObject* tmp = PyDict_GetItemString( userPythonizations, key->c_str() );
2780 Py_ssize_t num_pythonizations = PyList_Size( tmp );
2781 PyObject* arglist = nullptr;
2782 if ( num_pythonizations )
2783 arglist = Py_BuildValue( "O,s", pyclass, name.c_str() );
2784 for ( Py_ssize_t i = 0; i < num_pythonizations; ++i ) {
2785 PyObject* pythonizor = PyList_GetItem( tmp, i );
2786 // TODO: detail error handling for the pythonizors
2787 PyObject* result = PyObject_CallObject( pythonizor, arglist );
2788 if ( !result ) {
2789 pstatus = kFALSE;
2790 break;
2791 } else
2792 Py_DECREF( result );
2793 }
2794 Py_XDECREF( arglist );
2795 }
2796
2797 Py_DECREF( userPythonizations );
2798 Py_DECREF( pythonizationScope );
2799
2800
2801// phew! all done ...
2802 return pstatus;
2803}
void Class()
Definition: Class.C:29
SVector< double, 2 > v
Definition: Dict.h:5
#define R__EXTERN
Definition: DllImport.h:27
#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:1162
#define PYROOT_IMPLEMENT_STRING_PYTHONIZATION_CMP(type, name)
Definition: Pythonize.cxx:1211
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
int type
Definition: TGX11.cxx:120
#define gInterpreter
Definition: TInterpreter.h:538
#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 "std::vector"-like collection of values implementing handy operation to analyse them.
Definition: RVec.hxx:221
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:64
virtual TLeaf * GetLeaf(const char *name) const
Return pointer to the 1st Leaf named name in thisBranch.
Definition: TBranch.cxx:1652
virtual const char * GetClassName() const
Return the name of the user class whose content is stored in this branch, if any.
Definition: TBranch.cxx:1282
virtual char * GetAddress() const
Definition: TBranch.h:171
Int_t GetOffset() const
Definition: TBranch.h:192
TObjArray * GetListOfLeaves()
Definition: TBranch.h:204
The ROOT global object gROOT contains a list of all defined classes.
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:4824
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:4761
Int_t Size() const
Return size of object of this class.
Definition: TClass.cxx:5466
ClassInfo_t * GetClassInfo() const
Definition: TClass.h:404
TMethod * GetMethodAllAny(const char *method)
Return pointer to method without looking at parameters.
Definition: TClass.cxx:4237
Bool_t InheritsFrom(const char *cl) const
Return kTRUE if this class inherits from a class with name "classname".
Definition: TClass.cxx:4720
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:2885
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:200
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:32
virtual void * GetValuePointer() const
Definition: TLeaf.h:92
virtual const char * GetTypeName() const
Definition: TLeaf.h:93
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:78
virtual Int_t GetNdata() const
Definition: TLeaf.h:90
TBranch * GetBranch() const
Definition: TLeaf.h:75
virtual Int_t GetLenStatic() const
Return the fixed length of this leaf.
Definition: TLeaf.h:86
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:165
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
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:2286
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:578
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:539
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:847
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:702
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:1754
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:1390
R__EXTERN PyObject * gRootModule
Definition: ObjectProxy.cxx:39
double TFNPyCallback(void *vpyfunc, Long_t npar, double *a0, double *a1)
Definition: Pythonize.cxx:1784
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:2348
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