Python Forum

Full Version: Is it OK to use a context manager to simplify attribute access?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In a Jupyter notebook, I have 5 or 10 line fragments performing some relatively simple arithmetic. The purpose of the notebook is to teach engineering principles, not programming. I want the code to be as easy to read for inexperienced programmers as possible. I would rather not have a lot of statements of the form:
Ag = Plate.w * Plate.t
One way I can manage this is to setup objects with attributes providing the data:
Plate = ...
Plate.w = 100
Plate.t = 10
Then have the plate object be a context manager that inserts all its attributes as variables in
the global namespace, and cleans up at the end. So I can write something like:
with Plate:
    Ag = w*t
Is there anything dreadfully wrong with this?

(A typically notebook will have 20 or 30 cells, of about 5 or
10 lines each with expressions a bit more complicated.

I have an overly long page giving more of the context and some alternatives here