0

I have a bit of an odd use-case. I already have a context manager for all my CLI applications which provides a lot of useful non-functional concern tasks (e.g. config parsing, logging setup, response time calculation, etc), I call it BaseCLI as follows:

class BaseCLI(object):

   def __enter__(self):
       # ... a lot of stuff 
       return config

   def __exit__(self, type, value, traceback):
       # exit implementation

I also have a DynamicScope implementation similar to the one in this answer https://stackoverflow.com/a/63340335/1142881. I would like to plug a dynamic scope instance to be reused as part my existing BaseCLI to do FLOP counting ... how can I do that? The DynamicScope is also a context manager and ideally I would like to do:

from somewhere import myscope

with BaseClI(...) as config:
   with myscope.assign(flop_count=0):
       # ... count the flops in every inner scope

This I would need to do in every CLI instance and that's not ideal .. I would instead like to achieve the same effect from the BaseCLI __enter__ implementation but don't know how ...

SkyWalker
  • 13,729
  • 18
  • 91
  • 187

1 Answers1

1

If I understand correctly , maybe something like this?

class BaseCLI(object):

   def __init__(self, scope, ...):
       self._scope = scope

   def __enter__(self):
       self._scope.__enter__()
       # ... a lot of stuff 
       return config

   def __exit__(self, type, value, traceback):
       self._scope.__exit__(type, value, traceback)
       # exit implementation

from somewhere import myscope
with BaseCLI(myscope.assign(flop_count=0),...) as config

This will create the scope, and run it's _enter_ and _exit_ methods together with the BaseCLI class

Ron Serruya
  • 3,988
  • 1
  • 16
  • 26