Skip to content

Commit 36f90ca

Browse files
authored
expand example using @pythonize (#1049)
1 parent ad8fbbf commit 36f90ca

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

manual/python/index.md

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -408,14 +408,30 @@ The loading of C++ libraries can even be automated using the `__init__.py` of th
408408

409409
PyROOT allows to inject new behaviour in C++ user classes that are used from Python - this is known as "pythonizing" those C++ classes. The aim here is to make C++ classes more "pythonic" or easier to use from Python, for example by making a C++ class iterable in Python or by defining how its objects should be represented as strings in Python.
410410

411-
Pythonizations for C++ classes can be registered by providing a function, the "pythonizor", which is decorated with the `@pythonization` decorator. The decorator specifies to which class or classes the pythonization should be applied, and the pythonizor function contains the code that performs the pythonization. For instance, the following code snippet registers a pythonization for class `C` that adds a new attribute to that class:
411+
Pythonizations for C++ classes can be registered by providing a function, the "pythonizor", which is decorated with the `@pythonization` decorator. The decorator specifies to which class or classes the pythonization should be applied, and the pythonizor function contains the code that performs the pythonization. For instance, the following code snippet registers a pythonization for class `MyContainer` that adds `len` Python method and binds it to an appropriate C++ method.
412412

413413
```python
414+
import ROOT
415+
ROOT.gInterpreter.Declare('''
416+
class MyContainer {
417+
public:
418+
size_t GetSize() const { return m_vec.size(); }
419+
private:
420+
std::vector<double> m_vec;
421+
};
422+
''')
423+
424+
container = ROOT.MyContainer()
425+
len(container) # TypeError: object of type 'MyContainer' has no len()
426+
427+
# pythonize MyClass by adding `__len__` and binding it to `GetSize`
414428
from ROOT import pythonization
429+
@pythonization("MyContainer")
430+
def pythonize_two_classes(klass):
431+
klass.__len__ = klass.GetSize
415432

416-
@pythonization("C")
417-
def pythonizor_for_C(klass):
418-
klass.new_attr = 'New attribute' # injects a new attribute in the class
433+
container = ROOT.MyContainer()
434+
len(container) # 0
419435
```
420436

421437
The very same mechanism is used internally in ROOT to pythonize ROOT classes, and it can be applied to user classes too since ROOT v6.26.

0 commit comments

Comments
 (0)