| 143 | raise RuntimeError("generator didn't yield") from None |
| 144 | |
| 145 | def __exit__(self, typ, value, traceback): |
| 146 | if typ is None: |
| 147 | try: |
| 148 | next(self.gen) |
| 149 | except StopIteration: |
| 150 | return False |
| 151 | else: |
| 152 | try: |
| 153 | raise RuntimeError("generator didn't stop") |
| 154 | finally: |
| 155 | self.gen.close() |
| 156 | else: |
| 157 | if value is None: |
| 158 | # Need to force instantiation so we can reliably |
| 159 | # tell if we get the same exception back |
| 160 | value = typ() |
| 161 | try: |
| 162 | self.gen.throw(value) |
| 163 | except StopIteration as exc: |
| 164 | # Suppress StopIteration *unless* it's the same exception that |
| 165 | # was passed to throw(). This prevents a StopIteration |
| 166 | # raised inside the "with" statement from being suppressed. |
| 167 | return exc is not value |
| 168 | except RuntimeError as exc: |
| 169 | # Don't re-raise the passed in exception. (issue27122) |
| 170 | if exc is value: |
| 171 | exc.__traceback__ = traceback |
| 172 | return False |
| 173 | # Avoid suppressing if a StopIteration exception |
| 174 | # was passed to throw() and later wrapped into a RuntimeError |
| 175 | # (see PEP 479 for sync generators; async generators also |
| 176 | # have this behavior). But do this only if the exception wrapped |
| 177 | # by the RuntimeError is actually Stop(Async)Iteration (see |
| 178 | # issue29692). |
| 179 | if ( |
| 180 | isinstance(value, StopIteration) |
| 181 | and exc.__cause__ is value |
| 182 | ): |
| 183 | value.__traceback__ = traceback |
| 184 | return False |
| 185 | raise |
| 186 | except BaseException as exc: |
| 187 | # only re-raise if it's *not* the exception that was |
| 188 | # passed to throw(), because __exit__() must not raise |
| 189 | # an exception unless __exit__() itself failed. But throw() |
| 190 | # has to raise the exception to signal propagation, so this |
| 191 | # fixes the impedance mismatch between the throw() protocol |
| 192 | # and the __exit__() protocol. |
| 193 | if exc is not value: |
| 194 | raise |
| 195 | exc.__traceback__ = traceback |
| 196 | return False |
| 197 | try: |
| 198 | raise RuntimeError("generator didn't stop after throw()") |
| 199 | finally: |
| 200 | self.gen.close() |
| 201 | |
| 202 | class _AsyncGeneratorContextManager( |