How to use a python context manager inside a generator

前端 未结 2 1461
余生分开走
余生分开走 2021-02-18 15:26

In python, should with-statements be used inside a generator? To be clear, I am not asking about using a decorator to create a context manager from a generator function. I am as

2条回答
  •  余生分开走
    2021-02-18 16:03

    class CManager(object):
        def __enter__(self):
              print "  __enter__"
              return self
        def __exit__(self, exctype, value, tb):
            print "  __exit__; excptype: '%s'; value: '%s'" % (exctype, value)
            if exctype is None:
                return
    
            # only re-raise if it's *not* the exception that was
            # passed to throw(), because __exit__() must not raise
            # an exception unless __exit__() itself failed.  But throw()
            # has to raise the exception to signal propagation, so this
            # fixes the impedance mismatch between the throw() protocol
            # and the __exit__() protocol.
            #
            if sys.exc_info()[1] is not (value or exctype()):
                raise 
    

提交回复
热议问题