Skip to content

built-in support for callback/hook based updates #518

@jlumpe

Description

@jlumpe

For external library functions whose internals you do not have access to, frequently the only way to use them with tqdm is to pass a callback that updates the progress bar. This is a common enough use case that there is an example of it in the README.

I think a method should be added directly to the tqdm class to support this. The method would take an optional function to be wrapped and return a callback function. An example would be something like this:

with tqdm(total=100) as pbar:
    result = some_library_func(number_of_things=100, cb=pbar.callback())

    # Equivalent to:
    result = some_library_func(number_of_things=100, cb=lambda *args, **kw: pbar.update())

Where the callback function calls pbar.update(), but accepts and ignores any arguments the library function passes to it. In the case where the callback is some function that needs to return a value and is called may times, the method would simply wrap this function:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10000, 100))

# (I know tqdm already has Pandas integration)
with tqdm(total=df.shape[0]) as pbar:
    result = df.apply(pbar.callback(some_slow_func))

This enables very easy use with existing functions or lambda functions, without having to define a new wrapper function each time. Extensions could include taking the amount to update by from the return value of the function.

I can definitely contribute this myself, I just wanted to see if there is support for it before starting.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions