1# Licensed to the Apache Software Foundation (ASF) under one
2# or more contributor license agreements. See the NOTICE file
3# distributed with this work for additional information
4# regarding copyright ownership. The ASF licenses this file
5# to you under the Apache License, Version 2.0 (the
6# "License"); you may not use this file except in compliance
7# with the License. You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing,
12# software distributed under the License is distributed on an
13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14# KIND, either express or implied. See the License for the
15# specific language governing permissions and limitations
16# under the License.
17from __future__ import annotations
18
19import warnings
20from collections.abc import Generator
21from contextlib import contextmanager
22
23
24@contextmanager
25def capture_with_reraise() -> Generator[list[warnings.WarningMessage], None, None]:
26 """Capture warnings in context and re-raise it on exit from the context manager."""
27 captured_warnings = []
28 try:
29 with warnings.catch_warnings(record=True) as captured_warnings:
30 yield captured_warnings
31 finally:
32 if captured_warnings:
33 for cw in captured_warnings:
34 warnings.warn_explicit(
35 message=cw.message,
36 category=cw.category,
37 filename=cw.filename,
38 lineno=cw.lineno,
39 source=cw.source,
40 )