Python Forum
Is it OK to use a context manager to simplify attribute access?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it OK to use a context manager to simplify attribute access?
#1
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Context-sensitive delimiter ZZTurn 9 1,445 May-16-2023, 07:31 AM
Last Post: Gribouillis
  How does open context manager work? deanhystad 7 1,321 Nov-08-2022, 02:45 PM
Last Post: deanhystad
  Decimal context stevendaprano 1 1,038 Apr-11-2022, 09:44 PM
Last Post: deanhystad
  I want to simplify this python code into fewer lines, it's about string mandaxyz 5 2,118 Jan-15-2022, 01:28 PM
Last Post: mandaxyz
  How to access parent object attribute Pavel_47 2 8,712 Nov-19-2021, 09:36 PM
Last Post: deanhystad
Thumbs Up [SOLVED] Simplify condition test in if block? Winfried 2 1,710 Aug-25-2021, 09:42 PM
Last Post: Winfried
  Flattening attribute access ruy 5 2,064 Jun-25-2021, 08:26 PM
Last Post: ruy
  How to create an app manager _ShevaKadu 8 3,783 Nov-01-2020, 12:47 PM
Last Post: _ShevaKadu
  TextIOWrapper.tell() with Python 3.6.9 in context of 0D/0A fschaef 0 2,069 Mar-29-2020, 09:18 AM
Last Post: fschaef
  How can i simplify this code Jezani_VIII 4 2,760 Aug-25-2019, 02:23 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020