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