Last active
August 16, 2018 12:55
-
-
Save twolodzko/92e2addd5d45818e274a252739342056 to your computer and use it in GitHub Desktop.
tqdm Function decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from tqdm import tqdm | |
| def tqdm_function_decorator(*args, **kwargs): | |
| """ | |
| Decorate a function by adding a progress bar | |
| Parameters | |
| ---------- | |
| *args, **kwargs | |
| Parameters passed to tqdm. | |
| Returns | |
| ------- | |
| Decorated function. | |
| """ | |
| class PbarFuncDecorator(object): | |
| """ | |
| The decorator class. It takes a function as an input | |
| and decorates it, so every call invokes tqdm an update | |
| in progress bar. | |
| """ | |
| def __init__(self, func): | |
| self.func = func | |
| self.pbar = tqdm(*args, **kwargs) | |
| def __call__(self, *args, **kwargs): | |
| tmp = self.func(*args, **kwargs) | |
| self.pbar.update() | |
| return tmp | |
| return PbarFuncDecorator | |
| if __name__ == "__main__": | |
| from time import sleep | |
| def func_iterator(func, iters): | |
| for _ in range(iters): | |
| func() | |
| N_ITERS = 5 | |
| @tqdm_function_decorator(total=N_ITERS) | |
| def sleeper(): | |
| sleep(1) | |
| func_iterator(sleeper, N_ITERS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment