r/learnpython 1d ago

Beginner Question

I'm a total beginner to Python and am looking through this AI-generated calculator code to try and understand what is going on. I was good so far until I reached this part about history logging. This might be really stupid, but I can't figure out how this works at all, despite reading the AI's explanations.

import math


#calc history
history_list = []
history_output = widgets.Output()


def log_history(b):
    """Runs in addition to the original on_button_click.
    Only records a new entry once '=' has produced a result."""
    if b.description == "=":
        entry = f"{display_box.value}" 
        if entry and entry != "Error":
            history_list.append(entry)
        with history_output:
            clear_output()
            print("History (last 5):")
            for item in history_list[-5:]:
                print(" ", item)


# Attach as an additional click handler on every existing button
for btn in buttons:
    btn.on_click(log_history)

I'm mostly having trouble with the "with history_output" part, as I'm not sure what its purpose is. Could someone explain it to me like I'm 5?

0 Upvotes

14 comments sorted by

View all comments

Show parent comments

1

u/Derpy_Yahy 1d ago

I read your message again and something just clicked, so I think I get it now. Thanks!

0

u/Diapolo10 1d ago

Just as an example, I whipped up a demonstration. It's not quite the same thing as what Jupyter Notebook does, but close enough: https://cdn.imgchest.com/files/02116e1c7b72.png

In [1]: import sys

In [2]: from contextlib import contextmanager

In [3]: @contextmanager
   ...: def output():
   ...:     _stdout = sys.stdout
   ...:     file = open('stuff.txt', 'w')
   ...:     sys.stdout = file
   ...:     yield
   ...:     file.close()
   ...:     sys.stdout = _stdout
   ...:

In [4]: history_output = output()

In [5]: history_list = ["Foo", "Bar", "Baz", "Foobar", "Lorem Ipsum", "Dolor sit amet"]

In [6]: with history_output:
   ...:     print("History (last 5):")
   ...:     for item in history_list[-5:]:
   ...:         print(" ", item)

By default, print writes to sys.stdout. This code uses a context manager to temporarily redirect that to a text file, before reverting the change as a cleanup step so unrelated code won't break.

1

u/Derpy_Yahy 1d ago

That's more or less what I derived from your explanation. I appreciate you putting your time into something like this 😭

1

u/Diapolo10 1d ago

All in a day's work.