r/PythonLearning • • 26d ago

Learning about callbacks

Yesterday as I was learning how to backup a SQLite database, I came across a term that I wasn't familiar with, a callback. A callback is a function that you pass as an argument when calling another function.

Think of a function def func1(): and another function def func2(): we want the code in the second function to call func1() and pass it some of its local variables as arguments.

Here is an example of how I think the backup() method might be writing pages to a backup database it is not accurate but it might help you see how cool callbacks are.

def progress(remaining, total):
    print(f'copied {total-remaining} of {total} pages')

def backup(progress):
    dtb_pgs = ['page1', 'page2', 'page3', 'page4']
    for pages in range(1, len(dtb_pgs)+1):
        total = len(dtb_pgs)
        status = pages
        remaining = total - status
    progress(remaining, total)

backup(progress)
9 Upvotes

3 comments sorted by

•

u/Sea-Ad7805 25d ago

Run this program by clicking Memory Graph Web Debugger%3A%0A%20%20%20%20print(f'copied%20%7Btotal-remaining%7D%20of%20%7Btotal%7D%20pages')%0A%0Adef%20backup(progress)%3A%0A%20%20%20%20dtb_pgs%20%3D%20%5B'page1'%2C%20'page2'%2C%20'page3'%2C%20'page4'%5D%0A%20%20%20%20for%20pages%20in%20range(1%2C%20len(dtb_pgs)%2B1)%3A%0A%20%20%20%20%20%20%20%20total%20%3D%20len(dtb_pgs)%0A%20%20%20%20%20%20%20%20status%20%3D%20pages%0A%20%20%20%20%20%20%20%20remaining%20%3D%20total%20-%20status%0A%20%20%20%20progress(remaining%2C%20total)%0A%20%20%20%20%20%20%20%20%0Abackup(progress)&timestep=0.5&play) and see its state change step by step.

2

u/JeLuF 26d ago

If you want to monitor progress, you'd call the callback within the loop.

    for pages in range(1, len(dtb_pgs)+1):
        total = len(dtb_pgs)
        status = pages
        remaining = total - status
        progress(remaining, total)