Skip to content

Operations

Duqtools uses delayed operations for filesystem-changing operations. They are implemented mostly with decorators, but a function could be added directly to the op_queue.

Operation

Bases: LongDescription

Operation, simple class which has a callable action.

Usually not called directly but used through Operations.

__call__()

Execute the action with the args and kwargs.

Returns:

  • Operation –

    The operation that was executed

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def __call__(self) -> Operation:
    """Execute the action with the args and kwargs.

    Returns
    -------
    Operation
        The operation that was executed
    """
    if self.action:
        logger.debug(self.long_description)
        self.action(*self.args, **self.kwargs)  # type: ignore
    return self

Operations

Bases: deque

Operations Queue which keeps track of all the operations that need to be done.

It's basically dask_delayed, but custom made and a few drawbacks: The return value from an action is eventually discarded, communication between queue items is possible through references, or global values, but not really recommended, and no guidance for this is provided

n_actions property

Return number of actions (no no-op).

add(**kwargs)

Convenience Operation wrapper around .append().

from duqtools.operations import add_to_op_queue.

op_queue.add(action=print, args=('Hello World,),
description="Function that prints hello world")
Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
146
147
148
149
150
151
152
153
154
155
156
def add(self, **kwargs) -> None:
    """Convenience Operation wrapper around .append().

    ```python
    from duqtools.operations import add_to_op_queue.

    op_queue.add(action=print, args=('Hello World,),
    description="Function that prints hello world")
    ```
    """
    self.append(Operation(**kwargs))

add_no_op(description, extra_description=None)

Adds a line to specify an action will not be undertaken.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
158
159
160
161
162
163
164
165
def add_no_op(self,
              description: str,
              extra_description: str | None = None):
    """Adds a line to specify an action will not be undertaken."""
    self.add(action=None,
             description=description,
             extra_description=extra_description,
             style=NO_OP_STYLE)

append(item)

Restrict our diet to Operation objects only.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
183
184
185
186
187
188
189
190
191
def append(self, item: Operation):  # type: ignore
    """Restrict our diet to Operation objects only."""
    if self.enabled:
        logger.debug(
            f'Appended {item.description} to the operations queue')
        super().append(item)
    else:
        loginfo('- ' + item.long_description)
        item()

apply()

Apply the next operation in the queue and remove it.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
193
194
195
196
197
def apply(self) -> Operation:
    """Apply the next operation in the queue and remove it."""
    op = self.popleft()
    op()
    return op

apply_all()

Apply all queued operations and empty the queue.

and show a fancy progress bar while applying

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def apply_all(self) -> None:
    """Apply all queued operations and empty the queue.

    and show a fancy progress bar while applying
    """
    from tqdm import tqdm
    loginfo(style('Applying Operations', **HEADER_STYLE))  # type: ignore

    if CFG.quiet:
        return self._apply_all()

    with tqdm(total=self.n_actions, position=1) as pbar:
        pbar.set_description('Progress')

        with tqdm(bar_format='{desc}') as dbar:

            def callback(op):
                if not op.action:
                    return
                if not op.quiet:
                    dbar.set_description(op.long_description)
                pbar.update()

            self._apply_all(callback=callback)

check_unconfirmed_operations()

Safety check, it should never happen that operations are not executed.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
273
274
275
276
277
278
279
def check_unconfirmed_operations(self):
    """Safety check, it should never happen that operations are not
    executed."""
    if self:
        logwarning(
            style((f'There are still {self.n_actions} operations '
                   'in the queue at program exit!'), **HEADER_STYLE))

confirm_apply_all()

First asks the user if he wants to apply everything.

Returns:

  • bool ( did we apply everything or not ) –
Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def confirm_apply_all(self) -> bool:
    """First asks the user if he wants to apply everything.

    Returns
    -------
    bool: did we apply everything or not
    """
    # To print the descriptions we need to get them
    loginfo('')
    loginfo(style('Operations in the Queue:',
                  **HEADER_STYLE))  # type: ignore
    loginfo(style('========================',
                  **HEADER_STYLE))  # type: ignore
    for op in self:
        if not op.quiet:
            loginfo('- ' + op.long_description)

    for warning in self.warnings:
        loginfo('- ' + warning.long_description)

    if self.dry_run:
        loginfo('Dry run enabled, not applying op_queue')
        return False

    # Do not confirm if all actions are no-op
    if all(op.action is None for op in self):
        loginfo('\nNo actions to execute.')
        return False

    if n_no_op := sum(op.action is None for op in self):
        loginfo(
            f'\nThere are {n_no_op} operations that will not be applied.')

    is_confirmed = self.yes or click.confirm(
        f'\nDo you want to apply all {self.n_actions} operations?',
        default=False)

    if is_confirmed:
        self.apply_all()

    return is_confirmed

info(description, extra_description=None)

Adds an info line.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
167
168
169
170
171
172
def info(self, description: str, extra_description: Optional[str] = None):
    """Adds an info line."""
    self.add(action=None,
             description=description,
             extra_description=extra_description,
             style=INFO_STYLE)

put(item)

Synonym for append.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
179
180
181
def put(self, item: Operation):
    """Synonym for append."""
    self.append(item)

Warning

Bases: LongDescription

Warning item for screen log.

add_to_op_queue(op_desc, extra_desc=None, quiet=False)

Decorator which adds the function call to the op_queue, instead of executing it directly, the string can be a format string and use the function arguments.

from duqtools.operations import add_to_op_queue, op_queue

@add_to_op_queue("Printing hello world", "{name}")
def print_hello_world(name):
    print(f"Hello World {name}")


print_hello_world("Snoozy")

op_queue.confirm_apply_all()
Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def add_to_op_queue(op_desc: str, extra_desc: str | None = None, quiet=False):
    """Decorator which adds the function call to the op_queue, instead of
    executing it directly, the string can be a format string and use the
    function arguments.

    ```python
    from duqtools.operations import add_to_op_queue, op_queue

    @add_to_op_queue("Printing hello world", "{name}")
    def print_hello_world(name):
        print(f"Hello World {name}")


    print_hello_world("Snoozy")

    op_queue.confirm_apply_all()
    ```
    """

    def op_queue_real(func):

        def wrapper(*args, **kwargs) -> None:
            # For the description format we must convert args to kwargs
            sig = signature(func)
            args_to_kw = dict(zip(sig.parameters, args))
            fkwargs = kwargs.copy()
            fkwargs.update(args_to_kw)
            extra_formatted = None
            if extra_desc:
                extra_formatted = extra_desc.format(**fkwargs)
            op_formatted = op_desc.format(**fkwargs)

            # add the function to the queue
            op_queue.add(action=func,
                         args=args,
                         kwargs=kwargs,
                         description=op_formatted,
                         extra_description=extra_formatted,
                         quiet=quiet)

        return wrapper

    return op_queue_real

confirm_operations(func)

Decorator which confirms and applies queued operations after the function.

from duqtools.operations import confirm_operations, op_queue

@confirm_operations
def complicated_stuff()
    op_queue.add(action=print, args=('Hello World,),
            description="Function that prints hello world")
    op_queue.add(action=print, args=('Hello World again,),
            description="Function that prints hello world, again")
Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def confirm_operations(func):
    """Decorator which confirms and applies queued operations after the
    function.

    ```python
    from duqtools.operations import confirm_operations, op_queue

    @confirm_operations
    def complicated_stuff()
        op_queue.add(action=print, args=('Hello World,),
                description="Function that prints hello world")
        op_queue.add(action=print, args=('Hello World again,),
                description="Function that prints hello world, again")
    ```
    """

    def wrapper(*args, **kwargs):
        if op_queue.enabled:
            raise RuntimeError('op_queue already enabled')
        try:
            op_queue.enabled = True
            ret = func(*args, **kwargs)
            op_queue.confirm_apply_all()
            op_queue.clear()
            op_queue.enabled = False
        except Exception:
            op_queue.clear()
            op_queue.enabled = False
            raise
        return ret

    return wrapper

op_queue_context()

Context manager to enable the op_queue, and confirm_operations on exit Also disables the op_queue on exit.

Works more or less the same as the @confirm_operations decorator

Source code in /home/docs/checkouts/readthedocs.org/user_builds/duqtools/envs/latest/lib/python3.11/site-packages/duqtools/operations.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
@contextmanager
def op_queue_context():
    """Context manager to enable the op_queue, and confirm_operations on exit
    Also disables the op_queue on exit.

    Works more or less the same as the `@confirm_operations` decorator
    """
    if op_queue.enabled:
        raise RuntimeError('op_queue already enabled')
    try:
        op_queue.enabled = True
        yield
        op_queue.confirm_apply_all()
        op_queue.clear()
        op_queue.enabled = False
    except Exception:
        op_queue.clear()
        op_queue.enabled = False
        raise