Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How it works...

All the work is done by the withprogressbar function. It acts as a decorator, so we can apply it to any function with the @withprogressbar syntax.

That is very convenient because the code that reports progress is isolated from the code actually doing the work, which allows us to reuse it in many different cases.

To make a decorator that interacts with the decorated function while the function itself is running, we relied on Python generators:

gen = func(*args, **kwargs)
while True:
    try:
        progress = next(gen)
    except StopIteration as exc:
        sys.stdout.write('\n')
        return exc.value
    else:
        # display the progressbar

When we call the decorated function (in our example, the wait function), we will be in fact calling _func_with_progress ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content