Déjà Queue
A fast alternative to multiprocessing.Queue. Faster, because it takes advantage of a shared memory ring buffer (rather than slow pipes) and pickle protocol 5 out-of-band data to minimize copies. dejaq.DejaQueue supports any type of picklable Python object, including numpy arrays or nested dictionaries with mixed content.
The speed advantage of DejaQueue becomes substantial for items of > 1 MB size. It enables efficient inter-job communication in big-data processing pipelines using dejaq.Actor or dejaq.Parallel.
Features:
- Fast, low-latency, high-throughput inter-process communication
- Supports any picklable Python object, including numpy arrays and nested dictionaries
- Zero-copy data transfer with pickle protocol 5 out-of-band data
- Picklable queue instances (queue object itself can be passed between processes)
- Actor class for remote method calls and attribute access in a separate process (see dejaq.Actor)
- Parallel pipelines: map functions or classes over iterables in pools of worker processes, stage after stage, with the data passed between the stages' processes directly (see dejaq.Parallel)
- Processing DAGs: split (
tee) and join (zip) pipeline stages, and feed them as data arrives, e.g. camera frames from aDejaQueueor a streaming actor (see Processing DAGs)
Auto-generated (minimal) API documentation: https://danionella.github.io/dejaq
Installation
-
conda install conda-forge::dejaq -
or, if you prefer pip:
pip install dejaq -
for development, clone this repository, navigate to the root directory and type
pip install -e .
dejaq supports Python 3.8 and later on Linux, macOS and Windows. On free-threaded Python builds (e.g. 3.14t), dejaq works, but on Linux and macOS importing it turns the GIL back on, because its dependency posix_ipc does not declare free-threading support yet (see #38).
Examples
dejaq.DejaQueue
import numpy as np
from multiprocessing import Process
from dejaq import DejaQueue
def produce(queue):
for i in range(10):
arr = np.random.randn(100,200,300)
data = dict(array=arr, i=i)
queue.put(data)
print(f'produced {type(arr)} {arr.shape} {arr.dtype}; meta: {i}; hash: {hash(arr.tobytes())}\n', flush=True)
def consume(queue, pid):
for data in queue: # until the queue is shut down and empty
array, i = data['array'], data['i']
print(f'consumer {pid} consumed {type(array)} {array.shape} {array.dtype}; index: {i}; hash: {hash(array.tobytes())}\n', flush=True)
if __name__ == "__main__":
queue = DejaQueue(buffer_bytes=100e6)
producer = Process(target=produce, args=(queue,))
consumers = [Process(target=consume, args=(queue, pid)) for pid in range(3)]
for c in consumers:
c.start()
producer.start()
producer.join()
queue.shutdown() # consumers finish the remaining items, then stop
for c in consumers:
c.join()
DejaQueue follows the interface of queue.Queue / multiprocessing.Queue:
put(obj, block=True, timeout=None),get(block=True, timeout=None),put_nowait(obj),get_nowait(),qsize(),empty(),full()shutdown(immediate=False)(as in Python 3.13): afterwardsput()raisesShutDown, andget()returns the remaining items and then raisesShutDown; this applies to all processes using the queue, and iterating over a queue ends there. Withimmediate=True, remaining items are dropped.- Exceptions:
dejaq.Empty,dejaq.Full,dejaq.ShutDown, which are alsoqueue.Empty,queue.Full(both alsoTimeoutError) and, on Python ≥ 3.13,queue.ShutDown - When the queue is full,
put(obj, on_full=...)chooses what happens:"block"(the default: wait, as set byblockandtimeout),"drop"(discardobj;putreturnsFalse),"drop_oldest"(discard the oldest items untilobjfits, e.g. to keep the newest camera frames when the consumer falls behind) or"flush"(discard all queued items).q.droppedcounts the items that this queue object'sput()discarded, and a warning (loggerdejaq.queues) reports them at most once a second, with the queue's name, e.g.queue 'frames': put(on_full='drop_oldest') dropped 187 items(give queues names withDejaQueue(..., name="frames"); a name can be in use by one queue at a time on a machine, so creating it again, e.g. by re-running a notebook cell before the old queue is gone, raisesFileExistsError). The warning is rate-limited (drops after the last warning are only reported with the next drop), so useq.droppedfor the exact count. Silence it withlogging.getLogger("dejaq").setLevel(logging.ERROR)in the process that drops, e.g. in a streaming actor's__init__. With a buffer that holds only one item (e.g.buffer_bytes=1.5 * frame.nbytes),"drop_oldest"keeps only the latest item. A stop item (e.g.None) can be discarded as well: end the stream withshutdown()instead. - Additionally:
get(peek_only=True)reads an item without removing it (a laterget()may get another item if a producer withon_full="drop_oldest"or"flush"discarded it meanwhile), andget(callback=fn)callsfnon the item while its numpy arrays still view the shared memory (zero-copy;fnmust not keep references to them) - A queue object can be pickled and passed to other processes, including independently started ones (
DejaQueue(name=..., create=False)attaches by name). It is removed once the creating object is garbage-collected, unless created withauto_unlink=False. It can also be used as a context manager. - It keeps working when a process using it dies, even while putting or getting an item.
dejaq.Actor and ActorDecorator
dejaq.Actor allows you to run a class instance in a separate process and call its methods or access its attributes remotely, as if it were local. This is useful for isolating heavy computations, stateful services, or legacy code in a separate process, while keeping a simple Pythonic interface.
Example: Using Actor directly
from dejaq import Actor
class Counter:
def __init__(self, start=0):
self.value = start
def increment(self, n=1):
self.value += n
return self.value
def get(self):
return self.value
# Start the actor in a separate process
counter = Actor(Counter, start=10)
print(counter.get()) # 10
print(counter.increment()) # 11
print(counter.increment(5)) # 16
print(counter.get()) # 16
counter.close() # Clean up the process
Example: Using ActorDecorator
from dejaq import ActorDecorator
@ActorDecorator
class Greeter:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, {self.name}!"
greeter = Greeter("Alice")
print(greeter.greet()) # "Hello, Alice!"
greeter.close()
Use with Actor(Counter) as counter: to close it automatically. An actor is also stopped when the Actor object is garbage-collected, and when your program exits. On stopping, the remote object's close() method is called, if it has one (the process is terminated if it has not ended after 10 s, see close(timeout=...)).
Features
- Remote method calls: Call methods as if the object was local. Exceptions raised by the remote method are raised again in your process, with the same type (and the remote traceback attached).
- Remote attribute access: Get and set attributes of the remote object (
counter.value,counter.value = 5). - Async calls:
counter.increment_async(5)returns aFuture(.result()waits for the value).counter.increment(5, noreply=True)does not wait at all (the result is discarded). Withnoreply=True, on_full="drop", the call is skipped (and returnsFalse) when the actor is too busy to take it, e.g. to send camera frames to a display actor without slowing the camera down. - Timeouts:
counter.get(timeout=2)raisesTimeoutErrorif there is no result within 2 s. If the actor's process has ended (it crashed or was closed), calls raisedejaq.remote.RemoteErrorinstead of waiting. - Threads and worker processes: An actor can be used from several threads, and passed to other processes (e.g. as an argument of a
Parallelfunction). - Zero-copy fast path: Pass
deepcopy=Falseto skip the default copy of numpy array arguments (e.g.actor.process(arr, deepcopy=False)). The method then reads the arrays directly in shared memory, which is only valid during the call: copy anything you want to keep (self.last = arr.copy()); returning a result computed from them is fine. ARuntimeWarningis shown if a method keeps a reference. - Streaming:
cam.grab_frame.stream(queue)switches a running actor to streaming (any method, with arguments if needed): from then on, it callsgrab_frame()whenever no call is waiting and puts each result intoqueue, which it returns. Calls such ascam.set_exposure(2.0)run between two results. See Processing DAGs below. - Tab completion: Works in Jupyter and most IDEs.
Running a function in worker processes: RemoteFunc
from dejaq import RemoteFunc
def square(x):
return x * x
with RemoteFunc(square, workers=4) as rf:
print(rf(12)) # 144
print(rf.map(range(5))) # [0, 1, 4, 9, 16]
print(rf.submit(7).result()) # 49
Notes:
- Each process that uses an actor (or a
RemoteFunc) gets a reply queue ofbuffer_bytes(default 10 MB) in shared memory. With many worker processes, choose a smallerbuffer_bytesif the results are small. - Arguments must be importable by the actor's process. In a notebook, a class defined in the notebook cannot be passed to an actor; such a call waits until its
timeout(an error is logged by the actor).
dejaq.Parallel
The following examples show how to use dejaq.Parallel to parallelize a function or a class, and how to create job pipelines.
Here we execute a function and map iterable inputs across 10 workers. To enable pipelining, the results of each stage are provided as iterable generator. Use .run() (or .compute()) to get the final result as a list. Results are in input order, unless you pass ordered=False (e.g. Parallel(n_workers=10, ordered=False)): then each result is returned as soon as it is ready, so that a slow item does not hold up the others.
from time import sleep
from dejaq import Parallel
def slow_function(arg):
sleep(1.0)
return arg + 5
input_iterable = range(100)
parallel_function = Parallel(n_workers=10)(slow_function)
stage = parallel_function(input_iterable)
result = stage.run() # or list(stage)
# or shorter:
result = Parallel(n_workers=10)(slow_function)(input_iterable).run()
If a worker raises an exception, run() (or iterating) raises the same exception, with the worker's traceback as its cause; if a worker process dies, it raises dejaq.parallel.WorkerError. A stage's workers are stopped when that happens, when the stage is closed (stage.close() or a with block; this also closes the stages that feed it) or garbage-collected, and at exit. Leaving a loop early (break) does not stop them: iterating again continues with the next result.
You can also use Parallel as a function decorator:
@Parallel(n_workers=10)
def slow_function_decorated(arg):
sleep(1.0)
return arg + 5
result = slow_function_decorated(input_iterable).run()
Similarly, you can decorate a class. It will be instantiated within a worker. Iterable items will be fed to the __call__ method. Note how the additional init arguments are provided:
@Parallel(n_workers=1)
class Reader:
def __init__(self, arg1):
self.arg1 = arg1
def __call__(self, item):
return item + self.arg1
result = Reader(arg1=0.5)(input_iterable).compute()
Finally, you can create pipelines of chained jobs. In this example, we have a single threaded reader and consumer, but a parallel processing stage (an example use case is sequentially reading a file, compressing chunks in parallel and then sequentially writing to an output file):
@Parallel(n_workers=1)
class Producer:
def __init__(self, arg1):
self.arg1 = arg1
def __call__(self, item):
return item + self.arg1
@Parallel(n_workers=10)
class Processor:
def __init__(self, arg1):
self.arg1 = arg1
def __call__(self, arg):
sleep(1.0) #simulating a slow function
return arg * self.arg1
@Parallel(n_workers=1)
class Consumer:
def __init__(self, arg1):
self.arg1 = arg1
def __call__(self, arg):
return arg - self.arg1
input_iterable = range(100)
stage1 = Producer(0.5)(input_iterable)
stage2 = Processor(10.0)(stage1)
stage3 = Consumer(1000)(stage2)
result = stage3.run()
# or:
result = Consumer(1000)(Processor(10.0)(Producer(0.5)(input_iterable))).run()
For large items such as camera frames (several MB each, at kHz rates), a few settings matter:
buffer_bytes: each stage's output queue. Make it at least about 10 times the item size, so that the stages can absorb each other's hiccups (a larger buffer does not make the steady state faster).zero_copy=True(stages withn_workers=1, e.g. a writer): the function receives each item from the input stage without a copy, its numpy arrays viewing the queue's memory. They are valid only during the call: copy what you need to keep (e.g. a previous frame), but returning them is fine. Likewise,for frame in stage.iter(zero_copy=True)in the main process, where each item is valid until the next one is requested. Zero-copy arrays may be unaligned in memory (e.g. float64 data not at a multiple of 8 bytes), which makes some numpy operations slower; copy them where that matters or a library needs aligned data.stage.qsize()tells how many results wait in a stage's output queue: one that stays near full means the next stage does not keep up. Stages themselves never drop items; to drop frames when the pipeline falls behind, put them into aDejaQueuewithon_full="drop_oldest"(see above) and pass the queue as the pipeline's input (Parallel(...)(fcn)(queue); it ends when the queue is shut down).- Each hop between processes copies an item once into a queue and once out of it, so fewer stages mean less copying;
teeandzipcopy each item only once. (Measured with 4 MB frames on CI runners:zipis 1.2-1.5x faster than with two copies on Windows and macOS, but 0.7x on Linux, for reasons not yet understood.)
A stage's results can be split into several branches with stage.tee(n), and stages can be combined with dejaq.parallel.zip(stage_a, stage_b) (which yields tuples). Like the stages themselves, both run in processes of their own, so the data does not pass through your main process. As with itertools.tee, consume the branches side by side: a branch that falls behind by more than its buffer holds makes the others wait.
Processing DAGs: pipelines with branches, fed as data arrives
Stages can be connected into a directed acyclic graph (DAG). Every node is a stage with worker processes of its own, stage.tee(n) splits a stage's results into branches, and dejaq.parallel.zip(...) joins branches into tuples. The data moves between the stages' processes directly; your main process only feeds the input and reads the end results.
Feeding a DAG through a DejaQueue
A DejaQueue as the input lets you feed items as they arrive, e.g. camera frames from a thread or a callback. The DAG starts processing at once, and finishes when the queue is shut down:
import threading
import numpy as np
from dejaq import DejaQueue, Parallel
from dejaq.parallel import zip as dzip
def subtract_background(frame):
return frame.astype(np.float32) - 100
def find_cells(frame):
return int((frame > 50).sum())
def mean_intensity(frame):
return float(frame.mean())
def combine(pair):
n_cells, intensity = pair
return {"cells": n_cells, "intensity": intensity}
if __name__ == "__main__":
frames = DejaQueue(buffer_bytes=10 * 8e6) # the DAG's input: room for ~10 frames
corrected = Parallel(n_workers=2, buffer_bytes=10 * 8e6)(subtract_background)(frames)
for_cells, for_intensity = corrected.tee(2) # fan-out: both branches get every frame
cells = Parallel(n_workers=4)(find_cells)(for_cells)
intensity = Parallel(n_workers=1)(mean_intensity)(for_intensity)
results = Parallel(n_workers=1)(combine)(dzip(cells, intensity)) # fan-in: one pair per frame
def acquire(): # e.g. a camera thread or callback
for i in range(100):
frame = np.random.randint(0, 255, (1024, 2048), np.uint16)
frames.put(frame, on_full="drop_oldest") # never blocks the camera
frames.shutdown() # end of input: the DAG finishes
threading.Thread(target=acquire).start()
for r in results: # results arrive as frames are processed
print(r)
print("frames dropped:", frames.dropped)
put(frame, on_full="drop_oldest")keeps the acquisition running when the DAG falls behind: the oldest waiting frames are dropped, andframes.droppedcounts them. With the defaulton_full="block", the acquisition waits instead, and no frame is lost.zippairs results one to one, in order. So each branch must yield exactly one result per input (returnNonerather than skipping an item), and stages before azipmust be ordered (the default).- Consume the branches of a
teeside by side (aszipdoes): a branch that falls behind by more than its buffer holds up the others. stage.qsize()shows how many results wait in a stage's output queue: a stage that stays near full is followed by one that doesn't keep up.- Size each stage's
buffer_bytesfor its results (about 10 times the result size, see above).
A streaming actor as the source
To run the acquisition in a process of its own, and still control it while it runs, use an actor and switch it to streaming. cam.grab_frame.stream(frames) makes the actor call grab_frame() whenever no call is waiting, and put each frame into frames, the DAG's input. Calls such as cam.set_exposure(2.0) run between two frames:
from dejaq import Actor, DejaQueue, Parallel
class Camera: # your camera class: any class works
def __init__(self, serial):
... # open the camera (runs in the actor's process)
def grab_frame(self, timeout_ms=10):
... # the next frame, or None if none came in time
def set_exposure(self, ms):
...
def process(frame):
...
if __name__ == "__main__":
frames = DejaQueue(buffer_bytes=10 * 4.2e6)
with Actor(Camera, "A123") as cam:
results = Parallel(n_workers=4)(process)(frames) # or a whole DAG, as above
cam.grab_frame.stream(frames, timeout_ms=10) # start streaming (arguments for grab_frame)
for i, r in enumerate(results):
if i == 100:
cam.set_exposure(2.0) # runs between two frames
if i == 1000:
cam.grab_frame.stream(None) # stop streaming
break
results.close()
- Any method can be streamed, with arguments:
cam.grab_frame.stream(frames, timeout_ms=10). A newstream(...)replaces the current one, andstream(None)stops it.stream()returns the queue, soParallel(...)(process)(cam.grab_frame.stream(DejaQueue(10 * 4.2e6)))works too. - When
framesis full, the newest frame is dropped by default, so the camera is never slowed down;on_full="drop_oldest"keeps the newest frames instead. (The actor never waits for space, since it serves calls between frames.) - Calls run between two frames, so the streamed method should return within a short time: use the camera's grab timeout, and return
Noneif no frame came (nothing is put then). A steady flood of calls holds the stream up, and the actor's_idle_functiondoes not run while it streams. - An error in the streamed method is logged, and the method is retried once a second; the actor stays controllable. Streaming stops, with a log message, if a frame cannot be put (the queue is shut down, the frame does not fit into it or cannot be pickled).
- When the actor stops (end of the
withblock,close(), or program exit),framesis shut down, so a DAG reading it finishes (also ifclose()has to terminate the actor; if the actor's process crashes, when theActoris closed or collected).stream(None)or a newstream(...)leave the queue open; a queue that was shut down already cannot be streamed into (ShutDown). - Dropped frames are counted and logged in the actor's process: there, not in your process,
frames.droppedgrows and the warning is printed (configure logging, if needed, in the class's__init__).
See also
Metadata
Release files for dejaq 1.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dejaq-1.1.0.tar.gz | 97.8 kB | Without provenance | Details for dejaq-1.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dejaq-1.1.0-py3-none-any.whl | Python 3 | none | any | Details for dejaq-1.1.0-py3-none-any.whl |
Total release size: 146.9 kB
Release files / dejaq-1.1.0.tar.gz
| Download URL | dejaq-1.1.0.tar.gz |
|---|---|
| Size | 97.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a6fffdc5577f6530a466250547cb2a1ac7c5b6277dabf360cbabf7ab4364bf8e
|
|
BLAKE2b-256 checksum How to use checksums |
25a00247b7330ff003991e8e0de61c9fa4eaf0abcc9805bb8f8c6f54e2bd21e9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / dejaq-1.1.0-py3-none-any.whl
| Download URL | dejaq-1.1.0-py3-none-any.whl |
|---|---|
| Size | 49.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6d977e7964187504ff347129a4198862ba9b2d01901a8791180ac743d72de7e2
|
|
BLAKE2b-256 checksum How to use checksums |
f276a844ca658fba66b710a3098afe8858f7c326fc0c11f73c6ed76b902beda3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for dejaq 1.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.