pycall
pycall |
Purpose
Call
a Python object,
e.g. a function, with optional input arguments and convert the result to a Mosel variable.
Synopsis
procedure pycall(expr:string,result:array|set|list[, arg1...])
procedure pycallvoid(expr:string[, arg1...])
function pycallbool(expr:string[, arg1...]):boolean
function pycallint(expr:string[, arg1...]):integer
function pycallreal(expr:string[, arg1...]):real
function pycallstr(expr:string[, arg1...]):string
function pycalltext(expr:string[, arg1...]):text
Arguments
expr
|
Global name of a callable Python object or Python expression that evaluates to a callable object
|
result
|
Result Mosel array, set or list
|
arg1, arg2,...
|
Optional input arguments for the object call
|
Example 1
The following example calls the Python
print and
max functions. The Mosel input arguments are automatically converted to Python objects and the return value of
max is converted to a Mosel real.
pycallvoid("print", "Python objects:", true, 1, 2.2, [3,4], {5}) writeln("max: ", pycallreal("max", [1.1, 7.7, 4.4]))
Example 2
The following example uses pandas to compute the mean value of two Mosel arrays. The Mosel input arrays are passed as a single list of arrays with compatible array indices and are automatically converted to a single pandas DataFrame. The return value of the
mean function is a pandas Series and its elements will be written to the Mosel
Result array.
declarations Input1, Input2, Result: array(range) of real end-declarations Input1 :: (0..4)[1, 2, 3, 4, 5] Input2 :: (0..4)[7, -1, -3, 1, 2] pyinitpandas pyexec("def mean(df, axis): return df.mean(axis)") pycall("mean", Result, [Input1, Input2], 1) writeln("mean: ", Result)
Further information
1. At first, the function interprets the expression string as a global Python object name and tries to access it by getting it from the attributes of the Python
__main__ module. If this fails, the expression is evaluated by Python. Then the expression result object will be called with the optional input arguments. Finally, the result of the object call is stored in or returned as a Mosel variable. This is equivalent to the Python expression:
It is a fatal error if the expression cannot be evaluated or if the object call or the type conversion between Python and Mosel fails.
expr(arg1, ...)
2. The first version of the
pycall routine stores the result in an array, set or list. Its behavior is additive: it writes the new elements to the existing Mosel array, set or list without clearing previously existing elements. Use
reset to manually clear an array, set or list before calling this function.
3. See the I/O
Driver python Section for further details about type conversions.
4. Do not concatenate untrusted strings from the end user into the
expr string. See Section
Xpress Insight configuration for more information.
Related topics
Module
python3