Guide¶
The Wolfram Client Library is structured in submodules all located in wolframclient
:
evaluation
provides convenient methods to evaluate Wolfram Language expressions directly from Python. There are many ways to evaluate code, including evaluation by a local kernel, direct evaluation by a public or private Wolfram Cloud or calling a deployed API.language
provides a Python representation of Wolfram Language symbols and functions.serializers
provides serialization methods to various formats such as string InputForm and binary WXF format.deserializers
contains a parser for WXF.exception
regroups the exceptions and errors that the library may raise.
Expression Representation¶
-
wolframclient.language.
wl
A factory of
WLSymbol
instances without any particular context.This instance of
WLSymbolFactory
is conveniently used by calling its attributes. The following code represents various Wolfram Language expressions:# Now wl.Now # Quantity[3, "Hours"] wl.Quantity(3, "Hours") # Select[PrimeQ, {1,2,3,4}] wl.Select(wl.PrimeQ, [1, 2, 3, 4])
Represent symbols in various contexts:
>>> wl.Developer.PackedArrayQ Developer`PackedArrayQ >>> wl.Global.f Global`f
Specify a context and a subcontext:
>>> wl.MyContext.MySubContext.SymbolName MyContext`MySubContext`SymbolName
-
wolframclient.language.
wlexpr
= <class 'wolframclient.language.expression.WLInputExpression'> Represent Wolfram Language expressions with input form strings.
Convenient alias for
WLInputExpression
.Represent an expression:
>>> wlexpr('Select[Range[10], EvenQ]') (Select[Range[10], EvenQ])
Represent a pure function that squares an input argument:
>>> wlexpr('# ^ 2 &' ) (# ^ 2 &)
-
wolframclient.language.
System
= System A factory of
WLSymbol
instances havingSystem`
context.See
WLSymbolFactory
for more details.Represent a symbol in the System context:
>>> System.ImageIdentify System`ImageIdentify
-
wolframclient.language.
Global
= Global A factory of
WLSymbol
instances havingGlobal`
context.See
WLSymbolFactory
andWLSymbolFactory
for more details.Represent a symbol in the Global context:
>>> Global.mySymbol Global`mySymbol
Represent a function call to a function:
>>> Global.myFunction('foo') Global`myFunction['foo']
-
class
wolframclient.language.expression.
WLSymbolFactory
(name=None)[source] Provide a convenient way to build objects representing arbitrary Wolfram Language expressions through the use of attributes.
This class is conveniently instantiated at startup as
wl
,Global
andSystem
. It should be instantiated only to represent many symbols belonging to the same specific context.Example:
>>> dev = WLSymbolFactory('Developer') >>> dev.PackedArrayQ Developer`PackedArrayQ
Alternative:
>>> wl.Developer.PackedArrayQ Developer`PackedArrayQ
Serialization¶
-
wolframclient.serializers.
export
(data, stream=None, target_format='wl', **options)[source] Serialize input data to a target format.
Input data can be any supported Python type, including
list
,dict
or any serializable Python object.Serializable python objects are class extending
WLSerializable
and types declared in an encoder.The default format is InputForm string:
>>> export(wl.Range(3)) b'Range[3]'
Specify WXF format by setting target_format:
>>> export([1,2,3], target_format='wxf') b'8:fsListCCC'
Note
WXF is a binary format for serializing Wolfram Language expression. Consult the format specifications for in depth format description.
WXF byte arrays are deserialized with
binary_deserialize()
:>>> wxf = export([1,2,3], target_format='wxf') >>> binary_deserialize(wxf) [1, 2, 3]
If stream is specified with a string, it is interpreted as a file path and the serialized form is written directly to the specified file. The file is opened and closed automatically:
>>> export([1, 2, 3], stream='file.wl') 'file.wl'
If stream is specified with an output stream, the serialization bytes are written to it.
Any object that implements a write method, e.g.
file
,io.BytesIO
orio.StringIO
, is a valid value for the stream named parameter:>>> with open('file.wl', 'wb') as f: ... export([1, 2, 3], stream=f) ... <open file 'file.wl', mode 'wb' at 0x10a4f01e0>
Formats¶
InputForm is the default format and is the most readable one:
>>> export([1, 2, 3], target_format = "wl")
'{1, 2, 3}'
Serialized output can be imported in a kernel using ToExpression.
WXF is also available as an efficient binary representation of Wolfram Language expressions:
>>> export([1, 2, 3], target_format = "wxf")
'8:f\x03s\x04ListC\x01C\x02C\x03'
The WXF format supports compression using zlib; the compression is disabled by default:
>>> export([1, 2, 3], target_format = "wxf", compress = True)
'8C:x\x9cKc.f\xf1\xc9,.qftfrf\x06\x00\x1b\xf8\x03L'
Serialized output can be imported in a kernel using BinaryDeserialize.
Supported Types¶
Built-in Data Types¶
Built-in data structures are all supported list
, set
, frozenset
and dict
.
Example:
>>> export({"list": [1, 2, 3], "set": set([1, 2, 2, 4]), "frozenset": frozenset([1, 2, 2, 4]), "dict": dict(a = 2)})
'<|"list" -> {1, 2, 3}, "set" -> {1, 2, 4}, "frozenset" -> {1, 2, 4}, "dict" -> <|"a" -> 2|>|>'
If no converter is defined for a class that has an __iter__ method, it is converted to a Wolfram Language List:
>>> export((i + 2 for i in range(10)))
'{2, 3, 4, 5, 6, 7, 8, 9, 10, 11}'
Python generators are also serialized as List:
>>> def gen():
... yield 1
... yield 2
...
>>> export(gen())
'{1, 2}'
Note
Python generators should preferably be used when serializing big data to avoid running out of memory.
To preserve ordering in associations use collections.OrderedDict
:
>>> from collections import OrderedDict
>>> export(OrderedDict([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]))
'<|0 -> "a", 1 -> "b", 2 -> "c", 3 -> "d"|>'
Numeric Types¶
Numeric types are natively supported; int
, float
, complex
and Decimal
serialize to
their Wolfram Language counterpart:
>>> export({'int': 1, 'float':2.3, 'decimal': decimal.Decimal(1), 'complex': complex(3, 4)})
'<|"int" -> 1, "float" -> 2.300000, "decimal" -> 1, "complex" -> Complex[3.000000, 4.000000]|>'
IEEE exceptions infinity and NaN are converted respectively to DirectedInfinity and Indeterminate:
>>> export({'+inf': float('inf'), '-inf': - float('inf'), 'nan': float('NaN')})
'<|"+inf" -> DirectedInfinity[1], "-inf" -> DirectedInfinity[-1], "nan" -> Indeterminate|>'
Fraction
serializes to Rational:
>>> export(fractions.Fraction(2, 3))
'(2 / 3)'
DateObject Serialization¶
datetime
, time
and date
are serialized to DateObject and all assume that the time zone to use is the current one at evaluation time:
>>> import datetime
>>> now = datetime.datetime.now()
>>> export([now.time(), now.date(), now])
'{TimeObject[{16, 1, 19.993822}, TimeZone -> $TimeZone], DateObject[{2018, 3, 16}], DateObject[{2018, 3, 16, 16, 1, 19.993822}, "Instant", "Gregorian", $TimeZone]}'
timedelta
is serialized to Quantity:
>>> export(datetime.timedelta(seconds = 340))
Specify a time zone in Python using pytz.timezone()
and serialize the date to a DateObject:
>>> from pytz import timezone
>>> export(timezone('US/Eastern').localize(datetime.datetime.now()))
'DateObject[{2018, 3, 16, 16, 4, 17.712409}, "Instant", "Gregorian", "US/Eastern"]'
Extensible Mechanism¶
The serializers
module provides mechanisms to extend built-in core functions and to define custom class serializations. There are three ways to extend serialization:
- Extend
WLSerializable
and override itsto_wl()
method. - Call
export()
with normalizer set to a normalizer function. This function will be applied to each object prior to the serialization process. - Declare a type encoder.
Serializable Classes¶
-
class
wolframclient.serializers.serializable.
WLSerializable
[source] A class that can be serialized using
export()
.Custom serialization of a class is done by subclassing this class:
from wolframclient.serializers.serializable import WLSerializable from wolframclient.language import wl from wolframclient.serializers import export class MyPythonClass(WLSerializable): def __init__(self, *arguments): self.arguments = arguments def to_wl(self): return wl.MyWolframFunction(*self.arguments)
Serialize
MyPythonClass
usingexport()
:>>> export(MyPythonClass('foo', 'bar')) b'MyWolframFunction["foo", "bar"]'
Serialization is applied recursively; arguments are also serialized:
>>> export(MyPythonClass(1, 2, MyPythonClass(2, 3))) 'MyWolframFunction[1, 2, MyWolframFunction[2, 3]]'
-
to_wl
()[source] Return the serialized form of a given Python class.
The returned value must be a combination of serializable types.
-
Normalizer¶
A normalizer is a function that takes one argument and returns one python object. It can either return a new object or pass the input if it can’t deal with that type.
Define a class:
class MyPythonClass(object):
def __init__(self, *arguments):
self.arguments = arguments
Define a normalizer function:
from wolframclient.language import wl
from wolframclient.serializers import export
def normalizer(o):
if isinstance(o, MyPythonClass):
return wl.MyWolframFunction(*o.arguments)
# don't forget to return the input if we can't deal with the type.
return o
Serialize an instance of MyPythonClass
using the normalizer function defined previously:
>>> export(MyPythonClass(1,2), normalizer=normalizer)
b'MyWolframFunction[1, 2]'
Encoder¶
The serialization of a Python object relies on encoder functions. Each encoder is attached to a set of Python types. Encoders are generators of bytes. The library defines encoders for most built-in Python types and for the core components of some popular libraries such as PIL Image
, NumPy arrays and Pandas Series
.
-
wolframclient.serializers.encoder.
wolfram_encoder
= <wolframclient.serializers.encoder.WolframDispatch object> Mapping between Python types and encoders used during serializations.
This instance of
Dispatch
is used inexport()
to serialize Python expressions and produce a stream of bytes.Register new encoders:
The annotation
dispatch()
applied to a function, defines an encoder and associates it to the types passed as argument of the annotation.Define a new class:
class MyPythonClass(object): def __init__(self, *arguments): self.arguments = arguments
Specify its encoder:
from wolframclient.serializers import wolfram_encoder from wolframclient.language import wl from wolframclient.serializers import export @wolfram_encoder.dispatch(MyPythonClass) def my_encoder(serializer, o): return serializer.encode(wl.MyWolframFunction(*o.arguments))
Serialize an expression:
>>> export(MyPythonClass(1,2)) b'MyWolframFunction[1, 2]'
Alternatively, apply
register()
to a function and its associated type(s) achieves the same result.It is not possible to associate two encoders with the same type, but it’s possible to remove a mapping. First, unregister the previous encoder:
wolfram_encoder.unregister(MyPythonClass)
And register it again with
register()
:wolfram_encoder.register(my_encoder, MyPythonClass)
Update with a dispatcher:
Another way to extend supported types is to create a new
Dispatch
, map various types and encoders and ultimately updatewolfram_encoder
usingupdate()
.Create a new dispatcher and register
MyPythonClass
:from wolframclient.utils.dispatch import Dispatch dispatch = Dispatch() dispatch.register(my_encoder, MyPythonClass)
Update the main encoder with the new dispatch instance:
wolfram_encoder.update(dispatch)
Serialize an expression:
>>> export(MyPythonClass(1,2)) b'MyWolframFunction[1, 2]'
Define plugins:
The library supports an entry point dedicated to new encoders: wolframclient_serializers_encoder. The library uses this entry point to loads plugins at runtime as separated libraries. For more information about entry points, refer to the documentation page about entry points.
The plugin name must be unique and the value must reference a dispatcher instance. This instance is loaded and used to update
wolfram_encoder
. A plugin is a simple way to distribute encoders as a separate library.One type must have a unique encoder associated to it; as a consequence, two plugins registering an encoder for the same type are incompatible. It is strongly advised to create one plugin for each existing Python library, e.g. have one plugin dedicated to NumPy and one to Pandas, which makes heavy use of NumPy arrays.
Deserialization¶
-
wolframclient.deserializers.
binary_deserialize
= <function binary_deserialize>[source] Deserialize binary data and return a Python object.
Serialize a Python object to WXF:
>>> wxf = export({'key' : [1,2,3]}, target_format='wxf')
Retrieve the input object:
>>> binary_deserialize(wxf) {'key': [1, 2, 3]}
A stream of
WXFToken
is generated from the WXF input by a instance ofWXFParser
.The consumer must be an instance of
WXFConsumer
. If none is provided,WXFConsumerNumpy
is used. To disable NumPy array support, useWXFConsumer
.Named parameters are passed to the consumer. They can be any valid parameter of
next_expression()
, namely:- dict_class: map WXF Association to dict_class in place of a regular
dict
- dict_class: map WXF Association to dict_class in place of a regular
Evaluating Expressions¶
-
class
wolframclient.evaluation.
WolframLanguageSession
(kernel=None, consumer=None, initfile=None, kernel_loglevel=0, stdin=-1, stdout=-1, stderr=-1, inputform_string_evaluation=True, wxf_bytes_evaluation=True, controller_class=<class 'wolframclient.evaluation.kernel.kernelcontroller.WolframKernelController'>, **kwargs)[source] A session to a Wolfram kernel enabling evaluation of Wolfram Language expressions.
Start a new session and send an expression for evaluation:
with WolframLanguageSession() as session: session.evaluate('Range[3]')
Set timeout to a number to set an evaluation timeout in seconds. If the evaluation time extends the timeout, a
TimeoutError
is raised.Evaluate an expression taking 10 seconds to return using a 5-second timeout:
long_evaluation = wl.Pause(10) with WolframLanguageSession() as session: session.evaluate(long_evaluation, timeout=5)
The asynchronous evaluation method
evaluate_future()
returns an instance ofFuture
class wrapping the evaluation result:with WolframLanguageSession() as session: future = session.evaluate_future('1+1') result = future.result()
When consumer is set to a
WXFConsumer
instance, this instance is passed tobinary_deserialize()
when deserializing the WXF output.By default, packed arrays are deserialized as
list
. Specify a consumer instance that supports NumPy arraysWXFConsumerNumpy
:from wolframclient.deserializers import WXFConsumerNumpy with WolframLanguageSession(consumer=WXFConsumerNumpy()) as session: numpy_array = session.evaluate('Range[3]')
Communication with a given kernel is based on ZMQ sockets:
- one PUSH socket to send expressions for evaluation
- one PULL socket to receive evaluation results
Kernel logging is disabled by default and is done through a third socket (type SUB). The initial log level is specified by the parameter kernel_loglevel. If the log level was not set at initialization, logging is not available for the entire session.
The kernel associated with a given session provides the following logging functions:
ClientLibrary`debug
corresponding tologging.Logger.debug()
ClientLibrary`info
corresponding tologging.Logger.info()
ClientLibrary`warn
corresponding tologging.Logger.warning()
ClientLibrary`error
corresponding tologging.Logger.error()
ClientLibrary`SetDebugLogLevel[]
send debug messages and aboveClientLibrary`SetInfoLogLevel[]
send info messages and aboveClientLibrary`SetWarnLogLevel[]
send warning messages and aboveClientLibrary`SetErrorLogLevel[]
only send error messagesClientLibrary`DisableKernelLogging[]
stop sending error message to the logging socket
The standard input, output and error file handles can be specified with stdin, stdout and stderr named parameters. Valid values are those accepted by
subprocess.Popen
(e.g.sys.stdout
). Those parameters should be handled with care as deadlocks can arise from misconfiguration.-
duplicate
()[source] Build a new instance using the same configuration as the one being duplicated.
-
evaluate
(expr, **kwargs)[source] Evaluate a given Wolfram Language expression.
-
evaluate_future
(expr, **kwargs)[source] Evaluate an expression and return a future object.
The future object result is the evaluated expression. See
evaluate()
.
-
evaluate_wrap
(expr, **kwargs)[source] Evaluate a given Wolfram Language expression and return a result object with the result and meta information.
-
evaluate_wrap_future
(expr, **kwargs)[source] Evaluate an expression and return a future object.
The future object result is the result object with the evaluated expression and meta information. See
evaluate_wrap()
.
-
evaluate_wxf
(expr, **kwargs)[source] Evaluate an expression and return the serialized expression.
This method does not deserialize the Wolfram kernel input.
-
evaluate_wxf_future
(expr, **kwargs)[source] Evaluate an expression and return a future object.
The future object result is the WXF serialization of the evaluated expression. See
evaluate_wxf()
.
-
get_parameter
(parameter_name)[source] Return the value of a given session parameter.
Session parameters are:
'STARTUP_TIMEOUT'
: time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.'TERMINATE_TIMEOUT'
: time to wait, in seconds, after theQuit[]
command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
-
restart
(block=True, timeout=None)[source] Restart a given evaluator by stopping it in cases where it is already started.
-
set_parameter
(parameter_name, parameter_value)[source] Set a new value for a given parameter. The new value only applies for this session.
Session parameters are:
'STARTUP_TIMEOUT'
: time to wait, in seconds, after the kernel startup is requested. Default is 20 seconds.'TERMINATE_TIMEOUT'
: time to wait, in seconds, after theQuit[]
command is sent to the kernel. The kernel is killed after this duration. Default is 3 seconds.
-
start
(block=True, timeout=None)[source] Start a kernel controller and eventually start a fresh one if the previous one was terminated.
Set block to
True
(default isFalse
) to wait for the kernel to be up and running before returning. Optionally, set a timeout in seconds. If the timeout is reached, aTimeoutError
will be raised and the kernel is terminated.
-
start_future
()[source] Request the Wolfram kernel to start and return a future object.
The result of the future object is
True
when the kernel is ready to evaluate input.
-
stop
()[source] Request the Wolfram kernel to stop gracefully.
-
stop_future
(gracefully=True)[source] Request the Wolfram kernel to stop and return a future object.
The result of the future object is
True
when the controller thread is no longer alive. Set gracefully toFalse
to request an immediate stop, eventually cancelling ongoing evaluations.
-
terminate
()[source] Request the Wolfram kernel to stop immediately.
Ongoing evaluations may be cancelled.
-
class
wolframclient.evaluation.
WolframLanguageAsyncSession
(kernel=None, consumer=None, loop=None, initfile=None, kernel_loglevel=0, stdin=-1, stdout=-1, stderr=-1, inputform_string_evaluation=True, **kwargs)[source] Evaluate expressions asynchronously using coroutines.
Asynchronous evaluations are provided through coroutines and the
asyncio
modules.Instances of this class can be managed with an asynchronous context manager:
async with WolframLanguageAsyncSession() as session: await session.evaluate('Now')
An event loop can be explicitly passed using the named parameter loop; otherwise, the one returned by
get_event_loop()
is used.Coroutines all run in a unique thread. Since a Wolfram kernel is single threaded, there can be only one evaluation at a time. In a sense, from the event loop point of view, evaluations are atomic operations. Even when many asynchronous sessions are started, the number of threads equals the number of kernel instances running and should not be problematic. Ensuring that only one thread runs all operations of a given Wolfram kernel significantly reduces the complexity of the code without any real drawback.
-
duplicate
()[source] Build a new instance using the same configuration as the one being duplicated.
-
evaluate
(expr, **kwargs)[source] Evaluate an expression asynchronously.
This method is a coroutine.
-
evaluate_future
(expr, **kwargs)[source] Evaluate an expression and return a future object.
The future object result is the evaluated expression. See
evaluate()
.
-
evaluate_many
(expr_list)[source] Evaluate a given list of Wolfram Language expressions.
The list is provided as an iterable object.
-
evaluate_wrap
(expr, **kwargs)[source] Evaluate an expression and return a result object asynchronously.
This method is a coroutine.
-
evaluate_wrap_future
(expr, **kwargs)[source] Evaluate an expression and return a future object.
The future object result is the result object with the evaluated expression and meta information. See
evaluate_wrap()
.
-
evaluate_wxf
(expr, **kwargs)[source] Evaluate an expression and return the WXF output asynchronously.
This method is a coroutine.
-
evaluate_wxf_future
(expr, **kwargs)[source] Evaluate an expression and return a future object.
The future object result is the WXF serialization of the evaluated expression. See
evaluate_wxf()
.
-
restart
()[source] Restart a given evaluator by stopping it in cases where it is already started.
-
start
()[source] Asynchronously start the session.
This method is a coroutine.
-
stop
()[source] Asynchronously stop the session (graceful termination).
This method is a coroutine.
-
terminate
()[source] Asynchronously terminate the session.
This method is a coroutine.
-
-
class
wolframclient.evaluation.
WolframEvaluatorPool
(async_evaluators=None, poolsize=4, load_factor=0, loop=None, async_language_session_class=<class 'wolframclient.evaluation.kernel.asyncsession.WolframLanguageAsyncSession'>, **kwargs)[source] A pool of kernels to dispatch one-shot evaluations asynchronously.
Evaluators can be specified in various ways: as a string representing the path to a local kernel, a
WolframCloudAsyncSession
or an instance of aWolframLanguageAsyncSession
. More than one evaluator specification can be provided in the form of an iterable object, yielding the abovementioned specification. If the number of evaluators is less than the requested pool size (poolsize), elements are duplicated until the requested number of evaluators is reached.Create a pool from a Wolfram kernel default location:
async with WolframEvaluatorPool() as pool: await pool.evaluate('$InstallationDirectory')
Create a pool from a specific Wolfram kernel:
async with WolframEvaluatorPool('/path/to/local/kernel') as pool: await pool.evaluate('1+1')
Create a pool from a cloud evaluator:
cloud_session = WolframCloudAsyncSession(credentials=myCredentials) async with WolframEvaluatorPool(cloud_session) as pool: await pool.evaluate('$MachineName')
Create a pool from a list of specifications:
evaluators = [ WolframCloudAsyncSession(credentials=myCredentials), '/path/to/local/kernel' ] async with WolframEvaluatorPool(evaluators) as pool: await pool.evaluate('$MachineName')
Set poolsize to the number of kernel instances. The requested size may not be reached due to licencing restrictions.
Set load_factor to specify how many workloads are queued per kernel before a new evaluation becomes a blocking operation. Values below or equal to 0 mean an infinite queue size.
Set loop to the event loop to use.
kwargs are passed to
WolframLanguageAsyncSession
during initialization.-
start
()[source] Start a pool of kernels and wait for at least one of them to be ready for evaluation.
This method is a coroutine. If not all the kernels were able to start, it fails and terminates the pool.
-
-
wolframclient.evaluation.
parallel_evaluate
(expressions, evaluator_spec=None, max_evaluators=4, loop=None)[source] Start a kernel pool and evaluate the expressions in parallel.
The pool is created with the value of evaluator_spec. The pool is automatically stopped when it is no longer needed. The expressions are evaluated and returned in order.
Note that each evaluation should be independent and not rely on any previous one. There is no guarantee that two given expressions evaluate on the same kernel.
-
class
wolframclient.evaluation.
WolframResult
(result=None, failure=None)[source] The most generic result object.
The actual result is returned via the method
get()
. If the result is a success, the field result is returned; otherwise, failure is returned and most likely contains an error message.-
get
()[source] Return the result or raise an exception based on the success status.
-
-
class
wolframclient.evaluation.
WolframAPIResponse
(response, decoder=None)[source] A generic API response.
This class is lazily constructed when the response body becomes available.
A decoder is inferred from the content type. Currently JSON and WXF formats are supported.
-
get
()[source] Return the result or raise an exception based on the success status.
-
-
class
wolframclient.evaluation.
WolframAPIResponseAsync
(response, decoder=None)[source] Asynchronous counterpart of
WolframAPIResponse
, awaiting for the response body.Most of the class logic is implemented in
WolframAPIResponse
, except the build method which has to be a coroutine.-
get
()[source] Return the result or raise an exception based on the success status.
This is a coroutine.
-
Cloud API¶
-
class
wolframclient.evaluation.
WolframCloudSession
(credentials=None, server=None, inputform_string_evaluation=True, oauth_session_class=None, xauth_session_class=None, http_sessionclass=None, max_workers=4)[source] Represent a session to a given cloud enabling simple API call.
This is the central class of the cloud evaluation package. It is initialized with a server instance representing a given cloud. By default, a session targets the Wolfram Public Cloud.
Most of the time it is necessary to authenticate with the server before issuing requests. A session supports two forms of authentication:
- 2-legged oauth using a secured authentication key
- xauth using the user ID and password
Calling an API is done through the method
call()
, which will return an instance ofWolframAPIResponse
. It is strongly advised to reuse a session to make multiple calls to mitigate the cost of initialization.max_workers can be specified and is passed to the
ThreadPoolExecutor
used for future methods.-
call
(api, input_parameters={}, files={}, target_format='wl', permissions_key=None, **kwargv)[source] Call a given API using the provided input parameters.
api can be a string url or a
tuple
(username, api name). The username is generally the Wolfram Language symbol$UserName
. The API name can be a UUID or a relative path, e.g. myapi/foo/bar.The input parameters are provided as a dictionary with string keys being the name of the parameters associated to their value.
Files are passed in a dictionary. Values can have multiple forms:
{'parameter name': file_pointer}
It is possible to explicitly specify a filename and a content type:
{'parameter name': ('filename', file_pointer, 'content-type')}
String can also be passed as files:
{'parameter name': ('filename', '...string...data...', 'content-type')}
It is possible to pass a
PermissionsKey
to the server alongside the query and get access to a given resource.
-
call_future
(api, input_parameters={}, target_format='wl', permissions_key=None, **kwargv)[source] Call a given API asynchronously and return a
Future
object.See
WolframCloudSession.call()
for more details about input parameters.
-
duplicate
()[source] Build a new instance using the same configuration as the one being duplicated.
-
evaluate
(expr, **kwargs)[source] Send expr to the cloud for evaluation and return the result.
expr can be a Python object serializable by
export()
or the string InputForm of an expression to evaluate.
-
evaluate_future
(expr, **kwargs)[source] Send expr to the cloud for asynchronous evaluation and return a
Future
object.expr can be a Python object serializable by
export()
or the string InputForm of an expression to evaluate.
-
evaluate_wrap
(expr, **kwargs)[source] Similar to
evaluate()
but return the result as aWolframCloudEvaluationResponse
.
-
evaluate_wrap_future
(expr, **kwargs)[source] Asynchronously call evaluate_wrap.
Return a
Future
object.
-
start
()[source] Start the evaluator.
Once this function is called, the evaluator must be ready to evaluate incoming expressions.
-
stop
()[source] Gracefully stop the evaluator. Try to stop the evaluator but wait for the current evaluation to finish first.
-
terminate
()[source] Immediately stop the evaluator, which will kill the running jobs, resulting in cancelled evaluations.
-
wolfram_api_call
(api, **kwargs)[source] Build an helper class instance to call a given API.
-
class
wolframclient.evaluation.
WolframAPICall
(target, api, permission_key=None)[source] Helper class to perform an API call using a cloud session.
-
perform
(**kwargs)[source] Make the API call and return the result.
-
perform_future
(**kwargs)[source] Make the API call asynchronously and return a future object.
-
-
class
wolframclient.evaluation.
WolframAPIResponse
(response, decoder=None)[source] A generic API response.
This class is lazily constructed when the response body becomes available.
A decoder is inferred from the content type. Currently JSON and WXF formats are supported.
-
get
()[source] Return the result or raise an exception based on the success status.
-
-
class
wolframclient.evaluation.
WolframCloudAsyncSession
(credentials=None, server=None, loop=None, inputform_string_evaluation=True, oauth_session_class=None, xauth_session_class=None, http_sessionclass=None, ssl_context_class=None)[source] Interact with a Wolfram Cloud asynchronously using coroutines.
Asynchronous cloud operations are provided through coroutines using modules
asyncio
and aiohttp.Instances of this class can be managed with an asynchronous context manager:
async with WolframCloudAsyncSession() as session: await session.call(...)
An event loop can be explicitly passed using the named parameter loop; otherwise, the one returned by
get_event_loop()
is used. The initialization options of the classWolframCloudSession
are also supported by this class.-
call
(api, input_parameters={}, files={}, target_format='wl', permissions_key=None, **kwargv)[source] Call a given API using the provided input parameters.
api can be a string url or a
tuple
(username, api name). The username is generally the Wolfram Language symbol$UserName
. The API name can be a UUID or a relative path, e.g. myapi/foo/bar.The input parameters are provided as a dictionary with string keys being the name of the parameters associated to their value.
Files are passed in a dictionary. Values can have multiple forms:
{'parameter name': file_pointer}
It is possible to explicitly specify a filename and a content type:
{'parameter name': ('filename', file_pointer, 'content-type')}
Bytes can also be passed as files:
{'parameter name': ('filename', b'...binary...data...', 'content-type')}
It is possible to pass a
PermissionsKey
to the server alongside the query and get access to a given resource.
-
duplicate
()[source] Build a new instance using the same configuration as the one being duplicated.
-
evaluate
(expr, **kwargs)[source] Send expr to the cloud for evaluation and return the result.
expr can be a Python object serializable by
export()
or the string InputForm of an expression to evaluate.
-
evaluate_wrap
(expr, **kwargs)[source] Similar to
evaluate()
but return the result as aWolframEvaluationJSONResponseAsync
.
-
wolfram_api_call
(api, **kwargs)[source] Build an helper class instance to call a given API.
-
Exceptions¶
-
class
wolframclient.exception.
WolframLanguageException
(payload, exec_info=None)[source] The most generic exception raised by the Wolfram Client Library.
This class is
WLSerializable
and will automatically serialize to a failure box when evaluated in Wolfram Desktop.-
to_wl
(*args, **opts)[source] Return the serialized form of a given Python class.
The returned value must be a combination of serializable types.
-
-
class
wolframclient.exception.
AuthenticationException
(response, msg=None)[source] Error in an authentication request.
-
class
wolframclient.exception.
WolframEvaluationException
(error, result=None, messages=[])[source] Error after an evaluation raising messages.
-
class
wolframclient.exception.
RequestException
(response, msg=None)[source] Error in an HTTP request.
-
class
wolframclient.exception.
SocketException
(payload, exec_info=None)[source] Error while operating on socket.