10.4.2 Run a User-Defined Python Function

Use the oml.do_eval function to run a user-defined input function that explicitly retrieves data or for which external data is not required.

The oml.do_eval function runs a user-defined Python function in a Python engine spawned and managed by the database environment.

The syntax of the oml.do_eval function is the following:

oml.do_eval(func, func_owner=None, graphics=False, **kwargs)

The func argument is the function to run. It may be one of the following:

  • A Python function

  • A string that is the name of a user-defined Python function in the OML4Py script repository

  • A string that defines a Python function
  • An oml.script.script.Callable object returned by the oml.script.load function

The optional func_owner argument is a string or None (the default) that specifies the owner of the registered user-defined Python function when argument func is a registered user-defined Python function name.

The graphics argument is a boolean that specifies whether to look for images. The default value is False.

With the **kwargs parameter, you can pass additional arguments to the func function. Special control arguments, which start with oml_, are not passed to the function specified by func, but instead control what happens before or after the running of the function.

See Also: About Special Control Arguments

The oml.do_eval function returns a Python object or an oml.embed.data_image._DataImage. If no image is rendered in the user-defined Python function, oml.do_eval returns whatever Python object is returned by the function. Otherwise, it returns an oml.embed.data_image._DataImage object.

See Also: About Output

Example 10-6 Using the oml.do_eval Function

This example defines a Python function that returns a Pandas DataFrame with the columns ID and RES. It then passes that function to the oml.do_eval function.

import pandas as pd
import oml

def return_df(num, scale):
    import pandas as pd
    id = list(range(0, int(num)))
    res = [i/scale for i in id]
    return pd.DataFrame({"ID":id, "RES":res})

res = oml.do_eval(func=return_df, scale = 100, num = 10)
type(res)

res

Listing for This Example

>>> import pandas as pd
>>> import oml
>>>
>>> def return_df(num, scale):
...     import pandas as pd
...     id = list(range(0, int(num)))
...     res = [i/scale for i in id]
...     return pd.DataFrame({"ID":id, "RES":res})
... 
>>>
>>> res = oml.do_eval(func=return_df, scale = 100, num = 10)
>>> type(res)
<class 'pandas.core.frame.DataFrame'>
>>>
>>> res
   ID  RES
0 0.0 0.00
1 1.0 0.01
2 2.0 0.02
3 3.0 0.03
4 4.0 0.04
5 5.0 0.05
6 6.0 0.06
7 7.0 0.07
8 8.0 0.08
9 9.0 0.09