|
| 1 | +# Copyright 2024 The Flax Authors. |
| 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 | +import functools |
| 16 | +import warnings |
| 17 | +from typing import TypeVar |
| 18 | +from collections.abc import Callable |
| 19 | + |
| 20 | +F = TypeVar('F', bound=Callable) |
| 21 | + |
| 22 | + |
| 23 | +def deprecated(new_fn: F) -> F: |
| 24 | + """Creates a deprecated alias for a renamed function. |
| 25 | +
|
| 26 | + .. deprecated:: |
| 27 | + This decorator is for marking functions as deprecated. The returned |
| 28 | + wrapper emits a :class:`DeprecationWarning` on every call and then |
| 29 | + delegates to ``new_fn``. |
| 30 | +
|
| 31 | + The returned callable copies the signature, type annotations, and |
| 32 | + docstring of ``new_fn``, with a deprecation notice prepended to the |
| 33 | + docstring. This keeps IDE autocomplete and type-checking working while |
| 34 | + clearly communicating that callers should migrate. |
| 35 | +
|
| 36 | + Args: |
| 37 | + new_fn: The current, non-deprecated function to delegate to. |
| 38 | +
|
| 39 | + Returns: |
| 40 | + A wrapper that emits a :class:`DeprecationWarning` and then calls |
| 41 | + ``new_fn`` with the same arguments. |
| 42 | +
|
| 43 | + Example:: |
| 44 | +
|
| 45 | + >>> from flax.nnx.deprecations import deprecated |
| 46 | + >>> def new_api(x): |
| 47 | + ... return x * 2 |
| 48 | + >>> old_api = deprecated(new_api) |
| 49 | + >>> old_api(3) # emits DeprecationWarning: use new_api instead |
| 50 | + 6 |
| 51 | +
|
| 52 | + """ |
| 53 | + |
| 54 | + @functools.wraps(new_fn) |
| 55 | + def wrapper(*args, **kwargs): |
| 56 | + warnings.warn( |
| 57 | + f'This function is deprecated. Use {new_fn.__qualname__} instead.', |
| 58 | + DeprecationWarning, |
| 59 | + stacklevel=2, |
| 60 | + ) |
| 61 | + return new_fn(*args, **kwargs) |
| 62 | + |
| 63 | + dep_notice = ( |
| 64 | + f'.. deprecated::\n' |
| 65 | + f' Use :func:`{new_fn.__qualname__}` instead.\n\n' |
| 66 | + ) |
| 67 | + wrapper.__doc__ = dep_notice + (new_fn.__doc__ or '') |
| 68 | + |
| 69 | + return wrapper # type: ignore[return-value] |
0 commit comments