Is it possible to access enclosing context manager?

后端 未结 3 1661
灰色年华
灰色年华 2020-12-16 12:01

There are essentially three ways to use the with statement:

Use an existing context manager:

with manager:
    pass

Create a contex

3条回答
  •  忘掉有多难
    2020-12-16 12:45

    If the context manager is a class and only ever has a single instance, then you could find it on the heap:

    import gc
    
    class ConMan(object):
        def __init__(self, name):
            self.name = name
    
        def __enter__(self):
            print "enter %s" % self.name
    
        def found(self):
            print "You found %s!" % self.name
    
        def __exit__(self, *args):
            print "exit %s" % self.name
    
    
    def find_single(typ):
        single = None
        for obj in gc.get_objects():
            if isinstance(obj, typ):
                if single is not None:
                    raise ValueError("Found more than one")
                single = obj
        return single
    
    
    
    def foo():
        conman = find_single(ConMan)
        conman.found()
    
    with ConMan('the-context-manager'):
        foo()
    

    (Disclaimer: Don't do this)

提交回复
热议问题