|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +def inherit_docs(source_class): |
| 17 | + """ |
| 18 | + A class decorator that copies docstrings from source_class to the |
| 19 | + decorated class for any methods or attributes that match names. |
| 20 | + """ |
| 21 | + |
| 22 | + def decorator(target_class): |
| 23 | + # 1. Steal the main class docstring if the target doesn't have one |
| 24 | + if not target_class.__doc__ and source_class.__doc__: |
| 25 | + target_class.__doc__ = source_class.__doc__ |
| 26 | + |
| 27 | + # 2. Iterate over all attributes in the source class |
| 28 | + for name, source_item in vars(source_class).items(): |
| 29 | + # Check if the target class has the same attribute |
| 30 | + if name in vars(target_class): |
| 31 | + target_item = getattr(target_class, name) |
| 32 | + |
| 33 | + # Only copy if the target doesn't have a docstring |
| 34 | + # and the source does |
| 35 | + if hasattr(target_item, "__doc__") and not target_item.__doc__: |
| 36 | + if hasattr(source_item, "__doc__") and source_item.__doc__: |
| 37 | + try: |
| 38 | + # Use functools.update_wrapper or manual assignment |
| 39 | + # for methods, properties, and static methods |
| 40 | + target_item.__doc__ = source_item.__doc__ |
| 41 | + except AttributeError: |
| 42 | + # Read-only attributes or certain built-ins |
| 43 | + # might skip docstring assignment |
| 44 | + pass |
| 45 | + |
| 46 | + return target_class |
| 47 | + |
| 48 | + return decorator |
0 commit comments