When numpy arrays are passed as arguments to apply or via data-movement methods, they are not
copied. This means that you must be careful if you are sending an array that you intend to work
on. PyZMQ does allow you to track when a message has been sent so you can know when it is safe
to edit the buffer, but IPython only allows for this.

It is also important to note that the non-copying receive of a message is read-only. That
means that if you intend to work in-place on an array that you have sent or received, you must
copy it. This is true for both numpy arrays sent to engines and numpy arrays retrieved as
results.

If you want to safely edit an array in-place after sending it, you must use the track=True
flag. IPython always performs non-copying sends of arrays, which return immediately. You must
instruct IPython track those messages at send time in order to know for sure that the send has
completed. AsyncResults have a sent property, and wait_on_send() method for
checking and waiting for 0MQ to finish with a buffer.

If IPython doesn’t know what to do with an object, it will pickle it. There is a short list of
objects that are not pickled: buffers/memoryviews, bytes objects, and numpy
arrays. These are handled specially by IPython in order to prevent extra in-memory copies of data. Sending
bytes or numpy arrays will result in exactly zero in-memory copies of your data (unless the data
is very small).

If you have an object that provides a Python buffer interface, then you can always send that
buffer without copying - and reconstruct the object on the other side in your own code. It is
possible that the object reconstruction will become extensible, so you can add your own
non-copying types, but this does not yet exist.

Just about anything in Python is pickleable. The one notable exception is objects (generally
functions) with closures. Closures can be a complicated topic, but the basic principle is that
functions that refer to variables in their parent scope have closures.

An example of a function that uses a closure:

deff(a):definner():# inner will have a closurereturnareturninnerf1=f(1)f2=f(2)f1()# returns 1f2()# returns 2

f1 and f2 will have closures referring to the scope in which inner was defined,
because they use the variable ‘a’. As a result, you would not be able to send f1 or f2
with IPython. Note that you would be able to send f. This is only true for interactively
defined functions (as are often used in decorators), and only when there are variables used
inside the inner function, that are defined in the outer function. If the names are not in the
outer function, then there will not be a closure, and the generated function will look in
globals() for the name:

defg(b):# note that `b` is not referenced in inner's scopedefinner():# this inner will *not* have a closurereturnareturninnerg1=g(1)g2=g(2)g1()# raises NameError on 'a'a=5g2()# returns 5

g1 and g2will be sendable with IPython, and will treat the engine’s namespace as
globals(). The pull() method is implemented based on this principle. If we did not
provide pull, you could implement it yourself with apply, by returning objects out
of the global namespace:

There are two principal units of execution in Python: strings of Python code (e.g. ‘a=5’),
and Python functions. IPython is designed around the use of functions via the core
Client method, called apply.

The principal method of remote execution is apply(), of
View objects. The Client provides the full execution and
communication API for engines via its low-level send_apply_message() method, which is used
by all higher level methods of its Views.

For executing strings of Python code, DirectView`salsoprovidean:meth:`execute and
a run() method, which rather than take functions and arguments, take Python strings.
execute takes a string of Python code to execute, and sends it to the Engine(s). run
is the same as execute, but for a file rather than a string. It is a wrapper that
does something very similar to execute(open(f).read()).

The principal extension of the Client is the View
class. The client is typically a singleton for connecting to a cluster, and presents a
low-level interface to the Hub and Engines. Most real usage will involve creating one or more
View objects for working with engines in various ways.

DirectViews can be created in two ways, by index access to a client, or by a client’s
view() method. Index access to a Client works in a few ways. First, you can create
DirectViews to single engines by accessing the client by engine id:

In [2]: rc[0]Out[2]: <DirectView 0>

You can also create a DirectView with a list of engines:

In [2]: rc[0,1,2]Out[2]: <DirectView [0,1,2]>

Other methods for accessing elements, such as slicing and negative indexing, work by passing
the index directly to the client’s ids list, so:

Since a Python namespace is a dict, DirectView objects provide
dictionary-style access by key and methods such as get() and
update() for convenience. This make the remote namespaces of the engines
appear as a local dictionary. Underneath, these methods call apply():

Sometimes it is useful to partition a sequence and push the partitions to
different engines. In MPI language, this is know as scatter/gather and we
follow that terminology. However, it is important to remember that in
IPython’s Client class, scatter() is from the
interactive IPython session to the engines and gather() is from the
engines back to the interactive IPython session. For scatter/gather operations
between engines, MPI should be used:

The LoadBalancedView is the class for load-balanced execution via the task scheduler.
These views always run tasks on exactly one engine, but let the scheduler determine where that
should be, allowing load-balancing of tasks. The LoadBalancedView does allow you to specify
restrictions on where and when tasks can execute, for more complicated load-balanced workflows.

Our primary representation of the results of remote execution is the AsyncResult
object, based on the object of the same name in the built-in multiprocessing.pool
module. Our version provides a superset of that interface.

The basic principle of the AsyncResult is the encapsulation of one or more results not yet completed. Execution methods (including data movement, such as push/pull) will all return
AsyncResults when block=False.

Return the result when it arrives. If timeout is not None and the
result does not arrive within timeout seconds then
TimeoutError is raised. If the remote call raised
an exception then that exception will be reraised as a RemoteError
by get().

While an AsyncResult is not done, you can check on it with its ready() method, which will
return whether the AR is done. You can also wait on an AsyncResult with its wait() method.
This method blocks until the result arrives. If you don’t want to wait forever, you can pass a
timeout (in seconds) as an argument to wait(). wait() will always return None, and
should never raise an error.

ready() and wait() are insensitive to the success or failure of the call. After a
result is done, successful() will tell you whether the call completed without raising an
exception.

If you want the result of the call, you can use get(). Initially, get()
behaves just like wait(), in that it will block until the result is ready, or until a
timeout is met. However, unlike wait(), get() will raise a TimeoutError if
the timeout is reached and the result is still not ready. If the result arrives before the
timeout is reached, then get() will return the result itself if no exception was raised,
and will raise an exception if there was.

Here is where we start to expand on the multiprocessing interface. Rather than raising the
original exception, a RemoteError will be raised, encapsulating the remote exception with some
metadata. If the AsyncResult represents multiple calls (e.g. any time targets is plural), then
a CompositeError, a subclass of RemoteError, will be raised.

Other extensions of the AsyncResult interface include convenience wrappers for get().
AsyncResults have a property, result, with the short alias r, which call
get(). Since our object is designed for representing parallel results, it is expected
that many calls (any of those submitted via DirectView) will map results to engine IDs. We
provide a get_dict(), which is also a wrapper on get(), which returns a dictionary
of the individual results, keyed by engine ID.

You can also prevent a submitted job from executing, via the AsyncResult’s
abort() method. This will instruct engines to not execute the job when it arrives.

The larger extension of the AsyncResult API is the metadata attribute. The metadata
is a dictionary (with attribute access) that contains, logically enough, metadata about the
execution.

Metadata keys:

timestamps

submitted

When the task left the Client

started

When the task started execution on the engine

completed

When execution finished on the engine

received

When the result arrived on the Client

note that it is not known when the result arrived in 0MQ on the client, only when it
arrived in Python via Client.spin(), so in interactive use, this may not be
strictly informative.

Information about the engine

engine_id

The integer id

engine_uuid

The UUID of the engine

output of the call

error

Python exception, if there was one

execute_input

The code (str) that was executed

execute_result

Python output of an execute request (not apply),
as a Jupyter message dictionary.

stderr

stderr stream

stdout

stdout (e.g. print) stream

And some extended information

status

either ‘ok’ or ‘error’

msg_id

The UUID of the message

after

For tasks: the time-based msg_id dependencies

follow

For tasks: the location-based msg_id dependencies

While in most cases, the Clients that submitted a request will be the ones using the results,
other Clients can also request results directly from the Hub. This is done via the Client’s
get_result() method. This method will always return an AsyncResult object. If the call
was not submitted by the client, then it will be a subclass, called AsyncHubResult.
These behave in the same way as an AsyncResult, but if the result is not ready, waiting on an
AsyncHubResult polls the Hub, which is much more expensive than the passive polling used
in regular AsyncResults.

The Hub sees all traffic that may pass through the schedulers between engines and clients.
It does this so that it can track state, allowing multiple clients to retrieve results of
computations submitted by their peers, as well as persisting the state to a database.

queue_status

You can check the status of the queues of the engines with this command.

There are a few actions you can do with Engines that do not involve execution. These
messages are sent via the Control socket, and bypass any long queues of waiting execution
jobs

abort

Sometimes you may want to prevent a job you have submitted from running. The method
for this is abort(). It takes a container of msg_ids, and instructs the Engines to not
run the jobs if they arrive. The jobs will then fail with an AbortedTask error.

clear

You may want to purge the Engine(s) namespace of any data you have left in it. After
running clear, there will be no names in the Engine’s namespace

shutdown

You can also instruct engines (and the Controller) to terminate from a Client. This
can be useful when a job is finished, since you can shutdown all the processes with a
single command.

Since the Client is a synchronous object, events do not automatically trigger in your
interactive session - you must poll the 0MQ sockets for incoming messages. Note that
this polling does not make any network requests. It performs a select
operation, to check if messages are already in local memory, waiting to be handled.

The method that handles incoming messages is spin(). This method flushes any waiting
messages on the various incoming sockets, and updates the state of the Client.

If you need to wait for particular results to finish, you can use the wait() method,
which will call spin() until the messages are no longer outstanding. Anything that
represents a collection of messages, such as a list of msg_ids or one or more AsyncResult
objects, can be passed as argument to wait. A timeout can be specified, which will prevent
the call from blocking for more than a specified time, but the default behavior is to wait
forever.

The client also has an outstanding attribute - a set of msg_ids that are awaiting
replies. This is the default if wait is called with no arguments - i.e. wait on all
outstanding messages.

Many parallel computing problems can be expressed as a map, or running a single program with
a variety of different inputs. Python has a built-in map(), which does exactly this,
and many parallel execution tools in Python, such as the built-in
multiprocessing.Pool object provide implementations of map. All View objects
provide a map() method as well, but the load-balanced and direct implementations differ.

Views’ map methods can be called on any number of sequences, but they can also take the block
and bound keyword arguments, just like apply(), but only as keywords.