wolframclient.utils package

Submodules

wolframclient.utils.api module

wolframclient.utils.asyncio module

wolframclient.utils.asyncio.create_task(coro)[source]

ensure_future using get_event_loop, so that it behaves similarly to create_task, and gets the same signature.

wolframclient.utils.asyncio.get_event_loop(loop=None)[source]
wolframclient.utils.asyncio.run(coro)[source]

wolframclient.utils.datastructures module

class wolframclient.utils.datastructures.Association[source]

Bases: OrderedDict

A OrderedDict that serializes to an Association

class wolframclient.utils.datastructures.Settings[source]

Bases: dict

Dictionary subclass enabling attribute lookup/assignment of keys/values.

For example:

>>> m = Settings({'foo': 'bar'})
>>> m.foo
'bar'
>>> m.foo = 'not bar'
>>> m['foo']
'not bar'

Settings objects also provide .first() which acts like .get() but accepts multiple keys as arguments, and returns the value of the first hit, e.g.:

>>> m = Settings({'foo': 'bar', 'biz': 'baz'})
>>> m.first('wrong', 'incorrect', 'foo', 'biz')
'bar'
class wolframclient.utils.datastructures.immutabledict[source]

Bases: dict

hashable dict implementation, suitable for use as a key into other dicts.

>>> h1 = immutabledict({"apples": 1, "bananas":2})
>>> h2 = immutabledict({"bananas": 3, "mangoes": 5})
>>> h1+h2
immutabledict(apples=1, bananas=3, mangoes=5)
>>> d1 = {}
>>> d1[h1] = "salad"
>>> d1[h1]
'salad'
>>> d1[h2]
Traceback (most recent call last):
...
KeyError: immutabledict(bananas=3, mangoes=5)
based on answers from

http://stackoverflow.com/questions/1151658/python-hashable-dicts

clear() None.  Remove all items from D.
pop(k[, d]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem(*args, **opts)

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(*args, **opts)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

wolframclient.utils.debug module

wolframclient.utils.debug.echo(x)[source]
wolframclient.utils.debug.print_elapsed_time(viewfunc)[source]
wolframclient.utils.debug.repeated_timing(function, *args, **opts)[source]
wolframclient.utils.debug.timed(function)[source]
wolframclient.utils.debug.timed_repeated(N=30)[source]

wolframclient.utils.decorators module

class wolframclient.utils.decorators.cached_property(func, name=None)[source]

Bases: object

Decorator that converts a method with a single self argument into a property cached on the instance.

Optional name argument allows you to make cached properties of other methods. (e.g. url = cached_property(get_absolute_url, name=’url’) )

wolframclient.utils.decorators.decorate(*func)[source]
wolframclient.utils.decorators.to_dict(fn)
wolframclient.utils.decorators.to_tuple(fn)

wolframclient.utils.dispatch module

class wolframclient.utils.dispatch.Dispatch[source]

Bases: object

A method dispatcher class allowing for multiple implementations of a function. Each implementation is associated to a specific input type.

Implementations are registered with the annotation dispatch().

The Dispatch class is callable, it behaves as a function that uses the implementation corresponding to the input parameter.

When a type is a subtype, the type and its parents are checked in the order given by __mro__ (method resolution order).

Example: method resolve() applied to an instance of collections.OrderedDict, check for the first implementation to match with collections.OrderedDict, then with dict, and ultimately to object.

Once the mapping is determined, it is cached for later use.

as_method()[source]

Return the dispatch as a class method.

Create a new dispatcher:

dispatch = Dispatcher()

Use the dispatcher as a class method:

class MyClass(object):
    myMethod = dispatch.as_method()

Call the class method:

o = MyClass()
o.myMethod(arg, *args, **kwargs)
clear()[source]

Reset the dispatcher to its initial state.

clear_cache()[source]
default_function(*args, **opts)[source]

Ultimately called when no type was found.

dispatch(*args, **opts)[source]

Annotate a function and map it to a given set of type(s).

Declare an implementation to use on bytearray input:

@dispatcher.dispatch(bytearray)
def my_func(...)

The default implementation is associated with object. Set a default:

@dispatcher.dispatch(object)
def my_default_func(...)

A tuple can be used as input to associate more than one type with a function. Declare a function used for both bytes and bytearray:

@dispatcher.dispatch((bytes, bytearray))
def my_func(...)

Implementation must be unique. By default, registering the same combination of types will raise an error. Set replace_existing to True to update the current mapping. Or, set keep_existing to True to ignore duplicate registration and keep the existing mapping.

register(function, types=<class 'object'>, keep_existing=False, replace_existing=False)[source]

Equivalent to annotation dispatch() but as a function.

resolve(arg)[source]

Return the implementation better matching the type the argument type.

unregister(types=<class 'object'>)[source]

Remove implementations associated with types.

update(dispatch, **opts)[source]

Update current mapping with the one from dispatch.

dispatch can be a Dispatch instance or a dict. **opts are passed to register()

validate_types(types)[source]

wolframclient.utils.encoding module

wolframclient.utils.encoding.concatenate_bytes(iterable_of_bytes, /)

Concatenate any number of bytes objects.

The bytes whose method is called is inserted in between each pair.

The result is returned as a new bytes object.

Example: b’.’.join([b’ab’, b’pq’, b’rs’]) -> b’ab.pq.rs’.

wolframclient.utils.encoding.encode(s, encoding='utf-8', errors='strict')[source]
wolframclient.utils.encoding.encode_default(s, encoding='utf-8', errors='strict')[source]
wolframclient.utils.encoding.safe_force_text(obj)[source]

wolframclient.utils.environment module

wolframclient.utils.environment.find_default_kernel_path()[source]

Look for the most recent installed kernel.

wolframclient.utils.environment.installation_version()[source]

wolframclient.utils.externalevaluate module

wolframclient.utils.externalevaluate.Bool(consumer, result)[source]
wolframclient.utils.externalevaluate.Call(consumer, result, *args)[source]
wolframclient.utils.externalevaluate.Cast(consumer, result, return_type)[source]
wolframclient.utils.externalevaluate.DelReference(consumer, input)[source]
wolframclient.utils.externalevaluate.Eval(consumer, code, constants={})[source]
class wolframclient.utils.externalevaluate.ExternalEvaluateConsumer(routes_registry={}, objects_registry={}, globals_registry={})[source]

Bases: WXFConsumerNumpy

builtin_routes = {'Bool': <function Bool>, 'Call': <function Call>, 'Cast': <function Cast>, 'DelReference': <function DelReference>, 'Eval': <function Eval>, 'FromArrow': <function FromArrow>, 'FromComplex': <function FromComplex>, 'FromGregorianDay': <function FromGregorianDay>, 'FromMissing': <function FromMissing>, 'FromRational': <function FromRational>, 'FromTodayTime': <function FromTodayTime>, 'FromUnixTime': <function FromUnixTime>, 'GetAttribute': <function GetAttribute>, 'GetItem': <function GetItem>, 'GetReference': <function GetReference>, 'Import': <function Import>, 'Len': <function Len>, 'MethodCall': <function MethodCall>, 'Partial': <function Partial>, 'Set': <function Set>, 'SetAttribute': <function SetAttribute>, 'SetItem': <function SetItem>}
consume_function(*args, **kwargs)[source]

Consume a WXFToken of type function.

Return a list if the head is symbol List, otherwise returns the result of build_function() applied to the head and arguments.

Usually custom parsing rules target Functions, but not List. To do so, it is recommended to override build_function().

dispatch_wl_object(route, *args)[source]
hook_symbol

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 and System. 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
wolframclient.utils.externalevaluate.FromArrow(consumer, bytes)[source]
wolframclient.utils.externalevaluate.FromComplex(consumer, a, b)[source]
wolframclient.utils.externalevaluate.FromGregorianDay(consumer, year, month, day)[source]
wolframclient.utils.externalevaluate.FromMissing(consumer)[source]
wolframclient.utils.externalevaluate.FromRational(consumer, a, b)[source]
wolframclient.utils.externalevaluate.FromTodayTime(consumer, unixtime, timezone)[source]
wolframclient.utils.externalevaluate.FromUnixTime(consumer, unixtime, timezone)[source]
wolframclient.utils.externalevaluate.GetAttribute(consumer, result, names)[source]
wolframclient.utils.externalevaluate.GetItem(consumer, result, names)[source]
wolframclient.utils.externalevaluate.GetReference(consumer, input)[source]
wolframclient.utils.externalevaluate.Import(consumer, path, attr=None)[source]
wolframclient.utils.externalevaluate.Len(consumer, result)[source]
wolframclient.utils.externalevaluate.MethodCall(consumer, result, names, *args)[source]
wolframclient.utils.externalevaluate.Module(code, type_ignores=[])[source]
wolframclient.utils.externalevaluate.Partial(consumer, result, *args)[source]
wolframclient.utils.externalevaluate.Set(consumer, value, *names)[source]
wolframclient.utils.externalevaluate.SetAttribute(consumer, result, name, value)[source]
wolframclient.utils.externalevaluate.SetItem(consumer, result, name, value)[source]
class wolframclient.utils.externalevaluate.SocketWriter(socket)[source]

Bases: object

keep_listening

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 and System. 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
send_side_effect(expr)[source]
write(bytes, chunk_size=819200)[source]
wolframclient.utils.externalevaluate.check_wl_symbol(expr, symbol)[source]
wolframclient.utils.externalevaluate.handle_message(socket, consumer)[source]
class wolframclient.utils.externalevaluate.registry[source]

Bases: dict

register_function(func)[source]
wolframclient.utils.externalevaluate.start_zmq_instance(port=None, write_to_stdout=True, **opts)[source]
wolframclient.utils.externalevaluate.start_zmq_loop(message_limit=inf, exception_class=None, routes_registry={}, **opts)[source]
wolframclient.utils.externalevaluate.to_external_object(instance, objects_registry, force_externalobject=False)[source]
wolframclient.utils.externalevaluate.unpack_optionals(args, symbol=Rule)[source]

wolframclient.utils.functional module

wolframclient.utils.functional.composition(*functions)[source]
wolframclient.utils.functional.first(iterable, default=None)[source]
wolframclient.utils.functional.flatten(*args)[source]
wolframclient.utils.functional.identity(x)[source]
wolframclient.utils.functional.is_iterable(obj, exclude_list=(<class 'str'>, ))[source]
wolframclient.utils.functional.iterate(*args)[source]
wolframclient.utils.functional.last(iterable, default=None)[source]
wolframclient.utils.functional.partition(iterable, n)[source]

Yield successive n-sized chunks from l.

wolframclient.utils.functional.riffle(iterable, separator)[source]
wolframclient.utils.functional.to_iterable(obj, exclude_list=(<class 'str'>, ))[source]

wolframclient.utils.importutils module

class wolframclient.utils.importutils.API(importer=<function safe_import_string>, **mapping)[source]

Bases: object

items()[source]
keys()[source]
values()[source]
wolframclient.utils.importutils.import_string(dotted_path)[source]

Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed.

wolframclient.utils.importutils.module_path(module, *args)[source]
wolframclient.utils.importutils.safe_import_string(f)[source]
wolframclient.utils.importutils.safe_import_string_and_call(f, *args, **kw)[source]

wolframclient.utils.json module

wolframclient.utils.lock module

wolframclient.utils.lock.Lock()[source]

wolframclient.utils.logger module

wolframclient.utils.logger.setup_logging_to_file(path, level=None)[source]

Setup a basic Python logging configuration to a given file.

wolframclient.utils.logger.str_trim(o, max_char=80)[source]

Return the string representation of an object, trimmed to keep up to max_char characters.

wolframclient.utils.packedarray module

class wolframclient.utils.packedarray.PackedArray[source]

Bases: ndarray

Wrapper class on top of NymPy ndarray used to preserve packed arrays when round-tripping them.

wolframclient.utils.require module

wolframclient.utils.require.installed_modules()[source]
wolframclient.utils.require.missing_requirements(*modules)[source]
wolframclient.utils.require.require(*modules)[source]
wolframclient.utils.require.require_module(*modules)[source]

wolframclient.utils.six module

wolframclient.utils.tests module

class wolframclient.utils.tests.TestCase(methodName='runTest')[source]

Bases: TestCase

wolframclient.utils.tests.path_to_file_in_data_dir(*args)[source]

wolframclient.utils.url module

wolframclient.utils.url.evaluation_api_url(server)[source]
wolframclient.utils.url.url_join(*fragments)[source]

Join fragments of a URL, dealing with slashes.

wolframclient.utils.url.user_api_url(server, api)[source]

Build an API URL from a user name and an API id.

Module contents