21. Python IntegrationΒΆ

This notebook explores some additional features related to Python integration in RAW.

For ease of demonstration, we will use the Python API directly.

[2]:
from rawapi import new_raw_client

cli = new_raw_client()

One notable feature is the integration of RAW types with Python types.

For instance, RAW collections automatically become Python collections:

[5]:
r = cli.query(' SELECT * FROM ["Hello", "World"] ')

print(list(r))
['Hello', 'World']

Collections can even be converted onto Numpy arrays, for ease of integration with AI/ML tools:

[20]:
cli.query(' (a: [[1,1],[2,2]]) ', np_arrays=True)
[20]:
OrderedDict([('a', [[1, 1], [2, 2]])])

RAW records automatically become Python dictionaries:

[7]:
r = cli.query(' (field1: 1, field2: "One") ')

r
[7]:
OrderedDict([('field1', 1), ('field2', 'One')])
[8]:
r['field1']
[8]:
1

Finally, RAW queries can also call out to Python functions directly.

This allows executing Python code as part of the RAW query.

For this, use the python(<arguments list>) -> $$$ <Python Code $$$ syntax in RQL.

The code in-between $$$ is Python code being executed server-side.

[23]:
cli.query("""
sum_in_python := \python(a: INT): STRING -> $$$
 return "This is Python code summing the number: " + str(a + 1)
$$$;

sum_in_python(2)
""")
[23]:
'This is Python code summing the number: 3'