Hacker News new | ask | show | jobs
by baq 595 days ago
it's using context managers to manage context i.e. state that is there but isn't needed to be referenced by code directly. it's the whole point. you can do it all with just functions or objects (doesn't matter, functions are objects in Python anyway) by design, context managers are there for DRY purposes.
1 comments

What's jarring me with the parent's example is the fact that the context managers must be holding global state.

It would feel a lot better if it was this, for example, where you use each context explicitly:

  from diagrams import Diagram
  from diagrams.aws.compute import EC2

  with Diagram("Simple Diagram") as d:
      d.add(EC2("web"))
As as the parent also suggests, this then doesn't really need the context management at all

  from diagrams import Diagram
  from diagrams.aws.compute import EC2

  d = Diagram("Simple Diagram")
  d.add(EC2("web"))
yeah but then you have to repeat yourself a lot:

   d.add(first)
   d.add(second)
   d.add(...)
you see redundancy and a misused language capability, I see a feature and a nice DSL.