| |
| |
| """Tools to aid in deprecating code.""" |
|
|
| from __future__ import annotations |
|
|
| import sys |
| import warnings |
| from argparse import SUPPRESS, Action |
| from dataclasses import dataclass, field |
| from functools import wraps |
| from types import ModuleType |
| from typing import TYPE_CHECKING |
|
|
| if TYPE_CHECKING: |
| from argparse import ArgumentParser, Namespace |
| from collections.abc import Callable |
| from typing import Any, ParamSpec, Self, TypeVar |
|
|
| from packaging.version import Version |
|
|
| T = TypeVar("T") |
| P = ParamSpec("P") |
|
|
| ActionType = TypeVar("ActionType", bound=type[Action]) |
|
|
| from . import __version__ |
|
|
|
|
| class DeprecatedError(RuntimeError): |
| pass |
|
|
|
|
| |
| |
| class DeprecationHandler: |
| _version: str | None |
| _version_tuple: tuple[int, ...] | None |
| _version_object: Version | None |
|
|
| def __init__(self: Self, version: str) -> None: |
| """Factory to create a deprecation handle for the specified version. |
| |
| :param version: The version to compare against when checking deprecation statuses. |
| """ |
| self._version = version |
| |
| |
| self._version_tuple = self._get_version_tuple(version) |
| self._version_object = None |
|
|
| @staticmethod |
| def _get_version_tuple(version: str) -> tuple[int, ...] | None: |
| """Return version as non-empty tuple of ints if possible, else None. |
| |
| :param version: Version string to parse. |
| """ |
| try: |
| return tuple(int(part) for part in version.strip().split(".")) or None |
| except (AttributeError, ValueError): |
| return None |
|
|
| def _version_less_than(self: Self, version: str) -> bool: |
| """Test whether own version is less than the given version. |
| |
| :param version: Version string to compare against. |
| """ |
| if self._version_tuple and (version_tuple := self._get_version_tuple(version)): |
| return self._version_tuple < version_tuple |
|
|
| |
| |
| |
| from packaging.version import parse |
|
|
| if self._version_object is None: |
| try: |
| self._version_object = parse(self._version) |
| except TypeError: |
| |
| self._version_object = parse("0.0.0.dev0+placeholder") |
| return self._version_object < parse(version) |
|
|
| def __call__( |
| self: Self, |
| deprecate_in: str, |
| remove_in: str, |
| *, |
| addendum: str | None = None, |
| stack: int = 0, |
| deprecation_type: type[Warning] = DeprecationWarning, |
| ) -> Callable[[Callable[P, T]], Callable[P, T]]: |
| """Deprecation decorator for functions, methods, & classes. |
| |
| :param deprecate_in: Version in which code will be marked as deprecated. |
| :param remove_in: Version in which code is expected to be removed. |
| :param addendum: Optional additional messaging. Useful to indicate what to do instead. |
| :param stack: Optional stacklevel increment. |
| """ |
|
|
| def deprecated_decorator(obj: Callable[P, T]) -> Callable[P, T]: |
| |
| category, message = self._generate_message( |
| deprecate_in=deprecate_in, |
| remove_in=remove_in, |
| prefix=f"{obj.__module__}.{obj.__qualname__}", |
| addendum=addendum, |
| deprecation_type=deprecation_type, |
| ) |
|
|
| |
| if not category: |
| raise DeprecatedError(message) |
|
|
| |
| isclass = False |
| func: Callable[P, T] |
| if isinstance(obj, type): |
| try: |
| func = obj.__init__ |
| except AttributeError: |
| |
| func = obj |
| else: |
| isclass = True |
| else: |
| func = obj |
|
|
| |
| @wraps(func) |
| def inner(*args: P.args, **kwargs: P.kwargs) -> T: |
| warnings.warn(message, category, stacklevel=2 + stack) |
|
|
| return func(*args, **kwargs) |
|
|
| if isclass: |
| obj.__init__ = inner |
| return obj |
| else: |
| return inner |
|
|
| return deprecated_decorator |
|
|
| def argument( |
| self: Self, |
| deprecate_in: str, |
| remove_in: str, |
| argument: str, |
| *, |
| rename: str | None = None, |
| addendum: str | None = None, |
| stack: int = 0, |
| deprecation_type: type[Warning] = DeprecationWarning, |
| ) -> Callable[[Callable[P, T]], Callable[P, T]]: |
| """Deprecation decorator for keyword arguments. |
| |
| :param deprecate_in: Version in which code will be marked as deprecated. |
| :param remove_in: Version in which code is expected to be removed. |
| :param argument: The argument to deprecate. |
| :param rename: Optional new argument name. |
| :param addendum: Optional additional messaging. Useful to indicate what to do instead. |
| :param stack: Optional stacklevel increment. |
| """ |
|
|
| def deprecated_decorator(func: Callable[P, T]) -> Callable[P, T]: |
| |
| category, message = self._generate_message( |
| deprecate_in=deprecate_in, |
| remove_in=remove_in, |
| prefix=f"{func.__module__}.{func.__qualname__}({argument})", |
| |
| addendum=( |
| f"Use '{rename}' instead." if rename and not addendum else addendum |
| ), |
| deprecation_type=deprecation_type, |
| ) |
|
|
| |
| if not category: |
| raise DeprecatedError(message) |
|
|
| |
| @wraps(func) |
| def inner(*args: P.args, **kwargs: P.kwargs) -> T: |
| |
| if argument in kwargs: |
| warnings.warn(message, category, stacklevel=2 + stack) |
|
|
| |
| value = kwargs.pop(argument, None) |
| if rename: |
| kwargs.setdefault(rename, value) |
|
|
| return func(*args, **kwargs) |
|
|
| return inner |
|
|
| return deprecated_decorator |
|
|
| def action( |
| self: Self, |
| deprecate_in: str, |
| remove_in: str, |
| action: ActionType, |
| *, |
| addendum: str | None = None, |
| stack: int = 0, |
| deprecation_type: type[Warning] = FutureWarning, |
| ) -> ActionType: |
| """Wraps any argparse.Action to issue a deprecation warning.""" |
|
|
| class DeprecationMixin(Action): |
| category: type[Warning] |
| help: str |
|
|
| def __init__(inner_self: Self, *args: Any, **kwargs: Any) -> None: |
| super().__init__(*args, **kwargs) |
|
|
| category, message = self._generate_message( |
| deprecate_in=deprecate_in, |
| remove_in=remove_in, |
| prefix=( |
| |
| |
| f"`{inner_self.option_strings[-1]}`" |
| if inner_self.option_strings |
| |
| else f"`{inner_self.dest}`" |
| ), |
| addendum=addendum, |
| deprecation_type=deprecation_type, |
| ) |
|
|
| |
| if not category: |
| raise DeprecatedError(message) |
|
|
| inner_self.category = category |
| inner_self.deprecation = message |
| if inner_self.help is not SUPPRESS: |
| inner_self.help = message |
|
|
| def __call__( |
| inner_self: Self, |
| parser: ArgumentParser, |
| namespace: Namespace, |
| values: Any, |
| option_string: str | None = None, |
| ) -> None: |
| |
| from conda.common.constants import NULL |
|
|
| if values is not NULL: |
| warnings.warn( |
| inner_self.deprecation, |
| inner_self.category, |
| stacklevel=7 + stack, |
| ) |
|
|
| super().__call__(parser, namespace, values, option_string) |
|
|
| return type(action.__name__, (DeprecationMixin, action), {}) |
|
|
| def module( |
| self: Self, |
| deprecate_in: str, |
| remove_in: str, |
| *, |
| addendum: str | None = None, |
| stack: int = 0, |
| ) -> None: |
| """Deprecation function for modules. |
| |
| :param deprecate_in: Version in which code will be marked as deprecated. |
| :param remove_in: Version in which code is expected to be removed. |
| :param addendum: Optional additional messaging. Useful to indicate what to do instead. |
| :param stack: Optional stacklevel increment. |
| """ |
| self.topic( |
| deprecate_in=deprecate_in, |
| remove_in=remove_in, |
| topic=self._get_module(stack)[1], |
| addendum=addendum, |
| stack=2 + stack, |
| ) |
|
|
| def constant( |
| self: Self, |
| deprecate_in: str, |
| remove_in: str, |
| constant: str, |
| value: Any, |
| *, |
| addendum: str | None = None, |
| stack: int = 0, |
| deprecation_type: type[Warning] = DeprecationWarning, |
| ) -> None: |
| """Deprecation function for module constant/global. |
| |
| :param deprecate_in: Version in which code will be marked as deprecated. |
| :param remove_in: Version in which code is expected to be removed. |
| :param constant: |
| :param value: |
| :param addendum: Optional additional messaging. Useful to indicate what to do instead. |
| :param stack: Optional stacklevel increment. |
| """ |
| |
| module, fullname = self._get_module(stack) |
| |
| category, message = self._generate_message( |
| deprecate_in=deprecate_in, |
| remove_in=remove_in, |
| prefix=f"{fullname}.{constant}", |
| addendum=addendum, |
| deprecation_type=deprecation_type, |
| ) |
|
|
| |
| if not category: |
| raise DeprecatedError(message) |
|
|
| |
| if isinstance( |
| fallback := getattr(module, "__getattr__", None), |
| _ConstantDeprecationRegistry, |
| ): |
| deprecations = fallback |
| else: |
| deprecations = _ConstantDeprecationRegistry(fullname, fallback) |
| module.__getattr__ = deprecations |
|
|
| deprecations.register(constant, message, category, stack, value) |
|
|
| def topic( |
| self: Self, |
| deprecate_in: str, |
| remove_in: str, |
| *, |
| topic: str, |
| addendum: str | None = None, |
| stack: int = 0, |
| deprecation_type: type[Warning] = DeprecationWarning, |
| ) -> None: |
| """Deprecation function for a topic. |
| |
| :param deprecate_in: Version in which code will be marked as deprecated. |
| :param remove_in: Version in which code is expected to be removed. |
| :param topic: The topic being deprecated. |
| :param addendum: Optional additional messaging. Useful to indicate what to do instead. |
| :param stack: Optional stacklevel increment. |
| """ |
| |
| category, message = self._generate_message( |
| deprecate_in=deprecate_in, |
| remove_in=remove_in, |
| prefix=topic, |
| addendum=addendum, |
| deprecation_type=deprecation_type, |
| ) |
|
|
| |
| if not category: |
| raise DeprecatedError(message) |
|
|
| |
| warnings.warn(message, category, stacklevel=2 + stack) |
|
|
| def _get_module(self: Self, stack: int) -> tuple[ModuleType, str]: |
| """Detect the module from which we are being called. |
| |
| :param stack: The stacklevel increment. |
| :return: The module and module name. |
| """ |
| try: |
| frame = sys._getframe(2 + stack) |
| except IndexError: |
| |
| pass |
| else: |
| |
| try: |
| filename = frame.f_code.co_filename |
| except AttributeError: |
| |
| pass |
| else: |
| |
| |
| for loaded in tuple(sys.modules.values()): |
| if not isinstance(loaded, ModuleType): |
| continue |
| if not hasattr(loaded, "__file__"): |
| continue |
| if loaded.__file__ == filename: |
| return (loaded, loaded.__name__) |
|
|
| |
| import inspect |
|
|
| module = inspect.getmodule(frame) |
| if module is not None: |
| return (module, module.__name__) |
|
|
| raise DeprecatedError("unable to determine the calling module") |
|
|
| def _generate_message( |
| self: Self, |
| deprecate_in: str, |
| remove_in: str, |
| prefix: str, |
| addendum: str | None, |
| *, |
| deprecation_type: type[Warning], |
| ) -> tuple[type[Warning] | None, str]: |
| """Generate the standardized deprecation message and determine whether the |
| deprecation is pending, active, or past. |
| |
| :param deprecate_in: Version in which code will be marked as deprecated. |
| :param remove_in: Version in which code is expected to be removed. |
| :param prefix: The message prefix, usually the function name. |
| :param addendum: Additional messaging. Useful to indicate what to do instead. |
| :param deprecation_type: The warning type to use for active deprecations. |
| :return: The warning category (if applicable) and the message. |
| """ |
| category: type[Warning] | None |
| if self._version_less_than(deprecate_in): |
| category = PendingDeprecationWarning |
| warning = f"is pending deprecation and will be removed in {remove_in}." |
| elif self._version_less_than(remove_in): |
| category = deprecation_type |
| warning = f"is deprecated and will be removed in {remove_in}." |
| else: |
| category = None |
| warning = f"was slated for removal in {remove_in}." |
|
|
| return ( |
| category, |
| " ".join(filter(None, [prefix, warning, addendum])), |
| ) |
|
|
|
|
| @dataclass |
| class _ConstantDeprecationRegistry: |
| """Registry of deprecated module constants. |
| |
| Serves as a module's __getattr__, issuing deprecation warnings |
| when registered constants are accessed. |
| """ |
|
|
| deprecations: dict[str, tuple[str, type[Warning], int, Any]] = field( |
| default_factory=dict, |
| init=False, |
| repr=False, |
| ) |
| fullname: str |
| fallback: Callable[[str], Any] | None |
|
|
| def __call__(self, name: str) -> Any: |
| if name in self.deprecations: |
| message, category, stacklevel, value = self.deprecations[name] |
| warnings.warn(message, category, stacklevel=stacklevel) |
| return value |
|
|
| if self.fallback: |
| return self.fallback(name) |
|
|
| raise AttributeError(f"module '{self.fullname}' has no attribute '{name}'") |
|
|
| def register( |
| self, |
| constant: str, |
| message: str, |
| category: type[Warning], |
| stack: int, |
| value: Any, |
| ) -> None: |
| |
| self.deprecations[constant] = (message, category, 2 + stack, value) |
|
|
|
|
| deprecated = DeprecationHandler(__version__) |
|
|