diff --git a/README.md b/README.md index 47dde13..1fe840e 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ object so `isinstance` keeps working through both paths: ```python from typing import TYPE_CHECKING, TypeAlias -from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases +from frequenz.core.warnings import DeprecatedAlias, deprecated_symbols # List the aliases, or star imports won't see them. __all__ = ["Decimal", "Rational"] @@ -211,7 +211,7 @@ else: # In the `else`, never at module level: a `__getattr__` mypy can see makes # every name it doesn't know in this module `Any`, typos in downstream # imports included. - __getattr__ = deprecated_aliases( + __getattr__ = deprecated_symbols( __name__, # Warns ".Decimal is deprecated. Use decimal.Decimal instead.", # `since` is for the documentation. @@ -223,6 +223,38 @@ else: ) ``` +To deprecate a module constant or type variable, pass a `DeprecatedSymbol` to +`deprecated_symbols()`. In this example, `TIMEOUT_SECONDS` still returns `30.0`, +but the warning tells callers to use `TIMEOUT`: + +```python +from datetime import timedelta +from typing import TYPE_CHECKING, Final + +from frequenz.core.warnings import DeprecatedSymbol, deprecated_symbols + +__all__ = ["TIMEOUT", "TIMEOUT_SECONDS"] + +TIMEOUT: Final = timedelta(seconds=30) + +# Private: `__getattr__` is only called for names the module doesn't have. +_TIMEOUT_SECONDS: Final = 30.0 + +if TYPE_CHECKING: + TIMEOUT_SECONDS: Final = _TIMEOUT_SECONDS +else: + __getattr__ = deprecated_symbols( + __name__, + # Warns "mypkg.TIMEOUT_SECONDS is deprecated. Use mypkg.TIMEOUT instead." + DeprecatedSymbol( + "TIMEOUT_SECONDS", + value=_TIMEOUT_SECONDS, + replacement="mypkg.TIMEOUT", + since="v1.5.0", + ), + ) +``` + And check in a test that a piece of code doesn't warn, without the `"error"` filter that would make `warnings.warn()` raise inside the code under test: diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 67f33e6..cb19b0f 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,15 +2,44 @@ ## Summary - +You can now warn callers when they use a deprecated module constant, type variable or type alias. ## Upgrading - +- Replace calls to `deprecated_aliases()` with `deprecated_symbols()`. The arguments stay the same. Calling the old function emits a deprecation warning. It will be removed in v2.0.0. ## New Features - +- Use `DeprecatedSymbol` for module attributes that cannot take the `@deprecated` decorator. You can pass `DeprecatedSymbol` and `DeprecatedAlias` entries to the same `deprecated_symbols()` call. Here is how to deprecate a timeout constant: + + ```python + from datetime import timedelta + from typing import TYPE_CHECKING, Final + + from frequenz.core.warnings import DeprecatedSymbol, deprecated_symbols + + __all__ = ["TIMEOUT", "TIMEOUT_SECONDS"] + + TIMEOUT: Final = timedelta(seconds=30) + + _TIMEOUT_SECONDS: Final = 30.0 + + if TYPE_CHECKING: + TIMEOUT_SECONDS: Final = _TIMEOUT_SECONDS + else: + __getattr__ = deprecated_symbols( + __name__, + # Warns "mypkg.TIMEOUT_SECONDS is deprecated. Use mypkg.TIMEOUT instead." + DeprecatedSymbol( + "TIMEOUT_SECONDS", + value=_TIMEOUT_SECONDS, + replacement="mypkg.TIMEOUT", + since="v1.5.0", + ), + ) + ``` + + Callers still get `value` when they use the deprecated name. Set `replacement` to the fully qualified name callers should use instead. Use `since` to record the version for documentation. To customize the warning, pass a `message` template with `{old}` and, if you provide a replacement, `{new}`. Without a replacement, the default warning is ` is deprecated.` Give callers a message that tells them what to do next. ## Bug Fixes diff --git a/mkdocs.yml b/mkdocs.yml index a1490e1..c5282f8 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -102,9 +102,7 @@ plugins: paths: ["src"] options: extensions: - - griffe_warnings_deprecated: - kind: deprecated - title: Deprecated + - griffe_frequenz_core.deprecations docstring_section_style: spacy inherited_members: true merge_init_into_class: false diff --git a/pyproject.toml b/pyproject.toml index 1069b1f..3b1bcc1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,7 @@ dev-formatting = ["black == 26.10.1", "isort == 9.0.2"] dev-mkdocs = [ "Markdown == 3.11.2", "black == 26.10.1", - "griffe-warnings-deprecated == 1.1.2", + "griffe-frequenz-core == 1.1.0", "mike == 2.2.0", "mkdocs-gen-files == 0.6.1", "mkdocs-literate-nav == 0.6.3", diff --git a/src/frequenz/core/warnings/__init__.py b/src/frequenz/core/warnings/__init__.py index e857750..2ba2252 100644 --- a/src/frequenz/core/warnings/__init__.py +++ b/src/frequenz/core/warnings/__init__.py @@ -11,11 +11,14 @@ common case of a library having to touch a symbol it deprecated itself. It also provides -[`deprecated_aliases`][frequenz.core.warnings.deprecated_aliases], to keep the old -import path of a symbol that moved to another module, or was renamed, working, -warning whoever uses it, with a -[`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias] entry saying where it -is now and since which version it is deprecated, and +[`deprecated_symbols`][frequenz.core.warnings.deprecated_symbols], to keep +module-level symbols that can't take a `@deprecated` decorator working, warning +whoever uses them: a [`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias] +entry keeps the old import path of a symbol that moved to another module, or was +renamed, saying where it is now, and a +[`DeprecatedSymbol`][frequenz.core.warnings.DeprecatedSymbol] entry deprecates a +symbol where it is, such as a type variable or a constant. Both say since which +version they are deprecated. There is also [`asserting_no_warnings`][frequenz.core.warnings.asserting_no_warnings] with its [`asserting_no_deprecations`][frequenz.core.warnings.asserting_no_deprecations] shortcut, to check in a test that a piece of code doesn't warn. @@ -61,14 +64,21 @@ def convert(value: str) -> int: """ from ._asserting import asserting_no_deprecations, asserting_no_warnings -from ._deprecated_aliases import DeprecatedAlias, deprecated_aliases +from ._deprecated_symbols import ( + DeprecatedAlias, + DeprecatedSymbol, + deprecated_aliases, + deprecated_symbols, +) from ._ignoring import ignoring_deprecations, ignoring_warnings __all__ = [ "DeprecatedAlias", + "DeprecatedSymbol", "asserting_no_deprecations", "asserting_no_warnings", "deprecated_aliases", + "deprecated_symbols", "ignoring_deprecations", "ignoring_warnings", ] diff --git a/src/frequenz/core/warnings/_deprecated_aliases.py b/src/frequenz/core/warnings/_deprecated_aliases.py deleted file mode 100644 index f8f7dd6..0000000 --- a/src/frequenz/core/warnings/_deprecated_aliases.py +++ /dev/null @@ -1,526 +0,0 @@ -# License: MIT -# Copyright © 2026 Frequenz Energy-as-a-Service GmbH - -"""Keeping the old import path of a symbol that moved to another module. - -See the package documentation for the background. -""" - -import importlib -import string -import warnings -from collections.abc import Callable -from dataclasses import dataclass -from types import ModuleType -from typing import Any, overload - - -@dataclass(frozen=True, init=False, slots=True) -class DeprecatedAlias: - """A symbol kept reachable from its old name. - - Each one is an entry for - [`deprecated_aliases`][frequenz.core.warnings.deprecated_aliases], which has the - examples. - - The symbol moved to another module, `new_module`, was renamed, `new_name`, or - both. Without `new_module` it is still in the module defining the alias, under - its new name. - - Reaching the alias warns with ` is deprecated. Use instead.`, with - fully qualified names, following the Frequenz deprecation guide, or with - `message` if something else is needed. - - `since`, the version the alias is deprecated since, is not part of the - warning: it is only there for the documentation. - [`griffe-frequenz-core`](https://github.com/frequenz-floss/griffe-frequenz-core) - reads it, together with where the symbol is now, to generate the alias' - `Deprecated:` notice, so `message` changes the warning only. To change the - notice, write a `Deprecated:` admonition by hand in the docstring of the alias - declared for type checkers, which replaces the generated one. - - Everything is checked when the alias is created rather than when it is - reached. - """ - - name: str - """The deprecated name, in the module defining the alias.""" - - new_module: str | None - """The fully qualified name of the module the symbol lives in now. - - `None` if it is still in the module defining the alias, under - [`new_name`][frequenz.core.warnings.DeprecatedAlias.new_name]. - """ - - new_name: str - """The name the symbol has now. - - The same as [`name`][frequenz.core.warnings.DeprecatedAlias.name] if it was not - renamed. - """ - - since: str | None - """The version the alias is deprecated since, or `None` if not given. - - It is only used for the documentation, never in the warning. - """ - - message: str | None - """The template for the warning message, or `None` for the standard one. - - It is formatted with `{old}` and `{new}`, the fully qualified names of the - alias and of the symbol it resolves to, as plain fields, without attributes, - indexes, conversions or format specs. - """ - - # One overload with `new_module` and one with only `new_name`, so a call with - # neither matches none of them. - @overload - def __init__( # noqa: D107 - self, - name: str, - /, - *, - new_module: str, - new_name: str | None = None, - since: str | None = None, - message: str | None = None, - ) -> None: ... - - @overload - def __init__( # noqa: D107 - self, - name: str, - /, - *, - new_module: None = None, - new_name: str, - since: str | None = None, - message: str | None = None, - ) -> None: ... - - def __init__( # noqa: DOC502 - self, - name: str, - /, - *, - new_module: str | None = None, - new_name: str | None = None, - since: str | None = None, - message: str | None = None, - ) -> None: - """Initialize this instance. - - At least one of `new_module` and `new_name` must be given. - - Args: - name: The deprecated name, in the module defining the alias. - new_module: The fully qualified name of the module the symbol lives in - now, if it moved out of the module defining the alias. - new_name: The name the symbol has now, if it was renamed. - since: The version the alias is deprecated since, such as `"v1.2.0"`, - for the documentation only. - message: The template for the warning message, replacing the standard - ` is deprecated. Use instead.`, formatted with `{old}` - and `{new}`, the fully qualified names of the alias and of the - symbol it resolves to, as plain fields, without attributes, - indexes, conversions or format specs. - - Raises: - TypeError: If an argument is not a string, or if neither `new_module` - nor `new_name` is given. - ValueError: If `name`, `new_name` or a part of `new_module` is not an - identifier, if `since` is empty, or if `message` is not a template - with only plain `{old}` and `{new}` fields. - """ - # The class is frozen, which blocks plain assignment here too. - object.__setattr__(self, "name", name) - object.__setattr__(self, "new_module", new_module) - object.__setattr__(self, "new_name", name if new_name is None else new_name) - object.__setattr__(self, "since", since) - object.__setattr__(self, "message", message) - self._validate(new_name) - - def format_message(self, *, old: str, new: str) -> str: - """Format the warning message for this alias. - - Args: - old: The fully qualified name of the alias. - new: The fully qualified name of the symbol it resolves to. - - Returns: - The alias' `message` formatted with `old` and `new`, or - ` is deprecated. Use instead.` if it has none. - """ - if self.message is None: - return f"{old} is deprecated. Use {new} instead." - return self.message.format(old=old, new=new) - - def _validate(self, new_name: str | None) -> None: - """Check the fields. - - Args: - new_name: The `new_name` given to `__init__()`, before it defaulted to - `name`, to tell whether it was given at all. - - Raises: - TypeError: If neither `new_module` nor `new_name` is given. - """ - if self.new_module is None and new_name is None: - raise TypeError( - f"the alias {self.name!r} needs new_module, new_name or both, " - "got neither" - ) - self._validate_name() - self._validate_new_module() - self._validate_new_name() - self._validate_since() - self._validate_message() - - def _validate_name(self) -> None: - """Check that `name` is an identifier. - - Raises: - TypeError: If it is not a string. - ValueError: If it is not an identifier. - """ - if not isinstance(self.name, str): - raise TypeError(f"alias names must be str, got {self.name!r}") - if not self.name.isidentifier(): - raise ValueError(f"alias names must be identifiers, got {self.name!r}") - - def _validate_new_module(self) -> None: - """Check that `new_module`, if given, is a module name. - - Raises: - TypeError: If it is not a string. - ValueError: If one of its dotted parts is not an identifier. - """ - if self.new_module is None: - return - if not isinstance(self.new_module, str): - raise TypeError( - f"the new_module of {self.name!r} must be a str, " - f"got {self.new_module!r}" - ) - if not all(part.isidentifier() for part in self.new_module.split(".")): - raise ValueError( - f"the new_module of {self.name!r} is not a module name: " - f"{self.new_module!r}" - ) - - def _validate_new_name(self) -> None: - """Check that `new_name` is an identifier. - - Raises: - TypeError: If it is not a string. - ValueError: If it is not an identifier. - """ - if not isinstance(self.new_name, str): - raise TypeError( - f"the new_name of {self.name!r} must be a str, got {self.new_name!r}" - ) - if not self.new_name.isidentifier(): - raise ValueError( - f"the new_name of {self.name!r} is not an identifier: " - f"{self.new_name!r}" - ) - - def _validate_since(self) -> None: - """Check that `since`, if given, is not empty. - - Raises: - TypeError: If it is not a string. - ValueError: If it is empty or blank. - """ - if self.since is None: - return - if not isinstance(self.since, str): - raise TypeError( - f"the since of {self.name!r} must be a str, got {self.since!r}" - ) - if not self.since.strip(): - raise ValueError(f"the since of {self.name!r} is empty") - - def _validate_message(self) -> None: - """Check that `message`, if given, is a template with plain `{old}` and `{new}`. - - Raises: - TypeError: If it is not a string. - ValueError: If it has a stray brace, or a replacement field other than a - plain `{old}` or `{new}`. - """ - if self.message is None: - return - if not isinstance(self.message, str): - raise TypeError( - f"the message of {self.name!r} must be a str, got {self.message!r}" - ) - problem = ( - f"the message of {self.name!r} must be a template with only plain " - f"{{old}} and {{new}} fields, got {self.message!r}" - ) - try: - # A stray brace raises here. - parsed = list(string.Formatter().parse(self.message)) - except ValueError as error: - raise ValueError(problem) from error - # Anything more than a plain field can fail depending on the names it is - # formatted with, which are only known when the alias is reached, so - # formatting it once here can't tell: `{old.missing}` raises - # `AttributeError`, and `{old:{new}}` makes the new name a format spec. - if not all( - field in (None, "old", "new") and not spec and conversion is None - for _, field, spec, conversion in parsed - ): - raise ValueError(problem) - - -def deprecated_aliases( # noqa: DOC502 - module: str, - /, - *aliases: DeprecatedAlias, - category: type[Warning] = DeprecationWarning, - stacklevel: int = 2, -) -> Callable[[str], Any]: - """Build a module `__getattr__` that warns about deprecated aliases. - - Use this for symbols that moved to another module, or were renamed, but should - keep working from their old import path, when a [`typing_extensions.deprecated`][] - decorator is not an option because the object is not yours to mark: decorating - it would deprecate it for everybody, including the users of its new home or name. - The alias also stays the very same object, so [`isinstance`][] keeps working - through both paths. - - Each [`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias] says where the - symbol is now and since which version the alias is deprecated, so aliases - deprecated in different releases are documented with their own version, and - can give their own warning message. - - Danger: - Follow the usage example structure strictly. In particular never drop - the `else:`, otherwise a type checker will see the `__getattr__` - assignment and treat every symbol in the module as [`Any`][typing.Any], - effectively disabling type checking for the entire module. - - Warning: Star imports - A star import (`from module import *`) only consults `__getattr__` for - the names listed in the module's `__all__`. Without an `__all__`, it - takes only the names the module defines itself, so the aliases silently - disappear from star imports, and code using them fails with a - [`NameError`][] instead of getting the deprecation warning. Keep every - alias in `__all__` until it is removed. - - Example: Usage - This is how a module that used to define `Decimal` itself, and now gets it - from [`decimal`][], keeps the old import path working: - - ```python - from typing import TYPE_CHECKING, TypeAlias - - from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases - - __all__ = ["Decimal"] # Keeps the alias in star imports - - if TYPE_CHECKING: - # Private import, only for type checkers - from decimal import Decimal as _Decimal - - Decimal: TypeAlias = _Decimal - else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias("Decimal", new_module="decimal", since="v1.2.0"), - ) - ``` - - Reaching `Decimal` through this module, say `mypkg.Decimal`, now emits a - `DeprecationWarning` saying `mypkg.Decimal is deprecated. Use - decimal.Decimal instead.` - - `since` doesn't change the warning: it is for - [`griffe-frequenz-core`](https://github.com/frequenz-floss/griffe-frequenz-core), - which documents the alias with a ``Deprecated since v1.2.0. Use - [`decimal.Decimal`][] instead.`` notice. - - Example: Renaming - When the symbol was also renamed on the way out, `new_name` gives the name - it has now: - - ```python - from typing import TYPE_CHECKING, TypeAlias - - from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases - - if TYPE_CHECKING: - from fractions import Fraction as _Fraction - - Rational: TypeAlias = _Fraction - else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias( - "Rational", - new_module="fractions", - new_name="Fraction", - since="v1.3.0", - ), - ) - ``` - - Without `new_module`, the symbol was renamed in this very module: - - ```python - from typing import TYPE_CHECKING, TypeAlias - - from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases - - - class Widget: - ... # Called Gadget before v1.4.0 - - - if TYPE_CHECKING: - Gadget: TypeAlias = Widget - else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias("Gadget", new_name="Widget", since="v1.4.0"), - ) - ``` - - Example: Custom message - When the standard warning is not enough, an alias can give its own - message, as a template that gets the fully qualified old and new names as - `{old}` and `{new}`: - - ```python - from typing import TYPE_CHECKING, TypeAlias - - from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases - - if TYPE_CHECKING: - from decimal import Decimal as _Decimal - - Decimal: TypeAlias = _Decimal - else: - __getattr__ = deprecated_aliases( - __name__, - DeprecatedAlias( - "Decimal", - new_module="decimal", - since="v1.2.0", - message="{old} is deprecated and will be removed in v2.0.0. " - "Use {new} instead.", - ), - ) - ``` - - The message replaces the warning only: the notice is still generated from - `since` and where the symbol is now. To say more in the documentation too, - write a `Deprecated:` admonition by hand in the docstring of `Decimal` in - the `if TYPE_CHECKING:` branch, which replaces the generated notice. - - Tip: Deprecating whole modules - This function can't be used to deprecate a whole module. If you need to - do that, you can keep a real `__init__.py` at the old path, with a - `__getattr__ = deprecated_aliases(...)` that includes all the symbols - that used to be reachable there. - - Warning: Security Warning - This function imports the modules the aliases point at, so the aliases are - as trusted as an `import` statement in this module. Write them out as - literals; don't build them from anything that comes from outside the - program. - - Args: - module: The fully qualified name of the module defining the aliases. - *aliases: The deprecated aliases, at least one, each with its own name. - category: The category of the warning to emit. - stacklevel: How far up the stack the warning is reported, counting from the - `__getattr__` itself. The default of 2 points at the code reaching for - the alias, and only needs raising if something wraps the returned - function. - - Returns: - A function suitable for use as the module's `__getattr__`. - - Raises: - TypeError: If an argument has the wrong type, including an alias that is - not a [`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias]. Also - later, when an alias is reached, if it resolves to a module rather than - to a symbol in one. - ValueError: If there are no aliases, if two of them have the same name, if - one points at another alias in the same module, itself included, or if - `stacklevel` is smaller than 1. - """ - if not isinstance(module, str): - raise TypeError(f"module must be a str, got {module!r}") - if not (isinstance(category, type) and issubclass(category, Warning)): - raise TypeError(f"category must be a Warning subclass, got {category!r}") - if not isinstance(stacklevel, int): - raise TypeError(f"stacklevel must be an int, got {stacklevel!r}") - if stacklevel < 1: - raise ValueError(f"stacklevel must be 1 or more, got {stacklevel!r}") - if not aliases: - raise ValueError(f"no aliases given for module {module!r}") - by_name: dict[str, DeprecatedAlias] = {} - for alias in aliases: - # Also what a mapping, the form this function used to take, runs into. - if not isinstance(alias, DeprecatedAlias): - raise TypeError(f"aliases must be DeprecatedAlias instances, got {alias!r}") - # A dict literal would keep the last of two entries silently; this is the - # one place that can tell. - if alias.name in by_name: - raise ValueError(f"alias {alias.name!r} is given more than once") - by_name[alias.name] = alias - for alias in aliases: - # Reaching it would call this `__getattr__` again, and never stop if the - # aliases point at each other. - if alias.new_module in (None, module) and alias.new_name in by_name: - raise ValueError( - f"the alias {alias.name!r} points at {module}.{alias.new_name}, " - "which is a deprecated alias too" - ) - - def module_getattr(name: str) -> Any: - """Return a deprecated alias, warning about its new location. - - Args: - name: The name being looked up in the module. - - Returns: - The aliased object. - - Raises: - AttributeError: If the name is not one of the deprecated aliases. - TypeError: If the alias resolves to a module, which this can't keep - reachable from its old path. - """ - alias = by_name.get(name) - if alias is None: - raise AttributeError(f"module {module!r} has no attribute {name!r}") - new_module = module if alias.new_module is None else alias.new_module - new = f"{new_module}.{alias.new_name}" - # Resolved before the warning is raised, so an alias that can't work says - # so instead of warning about a move that didn't happen. It also keeps the - # `TypeError` below from being masked by an "error" filter turning that - # warning into an exception first. - value = getattr(importlib.import_module(new_module), alias.new_name) - if isinstance(value, ModuleType): - raise TypeError( - f"the target of {module}.{name} is the module {new}, and this " - "aliases names, not modules: the import system never consults a " - f"package's __getattr__, so `import {module}.{name}` would fail " - f"anyway. Keep a real __init__.py at {module}.{name}, with the " - "aliases for the names it used to hold in it." - ) - warnings.warn( - alias.format_message(old=f"{module}.{name}", new=new), - category, - stacklevel=stacklevel, - ) - return value - - return module_getattr diff --git a/src/frequenz/core/warnings/_deprecated_symbols.py b/src/frequenz/core/warnings/_deprecated_symbols.py new file mode 100644 index 0000000..e4be9a8 --- /dev/null +++ b/src/frequenz/core/warnings/_deprecated_symbols.py @@ -0,0 +1,853 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Deprecating module-level symbols that can't take a `@deprecated` decorator. + +See the package documentation for the background. +""" + +import importlib +import string +import warnings +from collections.abc import Callable +from dataclasses import dataclass +from types import ModuleType +from typing import Any, overload + +from typing_extensions import deprecated + + +@dataclass(frozen=True, init=False, slots=True) +class DeprecatedAlias: + """A symbol kept reachable from its old name. + + Each one is an entry for + [`deprecated_symbols`][frequenz.core.warnings.deprecated_symbols], which has the + examples. + + The symbol moved to another module, `new_module`, was renamed, `new_name`, or + both. Without `new_module` it is still in the module defining the alias, under + its new name. + + Reaching the alias warns with ` is deprecated. Use instead.`, with + fully qualified names, following the Frequenz deprecation guide, or with + `message` if something else is needed. + + `since`, the version the alias is deprecated since, is not part of the + warning: it is only there for the documentation. + [`griffe-frequenz-core`](https://github.com/frequenz-floss/griffe-frequenz-core) + reads it, together with where the symbol is now, to generate the alias' + `Deprecated:` notice, so `message` changes the warning only. To change the + notice, write a `Deprecated:` admonition by hand in the docstring of the alias + declared for type checkers, which replaces the generated one. + + Everything is checked when the alias is created rather than when it is + reached. + """ + + name: str + """The deprecated name, in the module defining the alias.""" + + new_module: str | None + """The fully qualified name of the module the symbol lives in now. + + `None` if it is still in the module defining the alias, under + [`new_name`][frequenz.core.warnings.DeprecatedAlias.new_name]. + """ + + new_name: str + """The name the symbol has now. + + The same as [`name`][frequenz.core.warnings.DeprecatedAlias.name] if it was not + renamed. + """ + + since: str | None + """The version the alias is deprecated since, or `None` if not given. + + It is only used for the documentation, never in the warning. + """ + + message: str | None + """The template for the warning message, or `None` for the standard one. + + It is formatted with `{old}` and `{new}`, the fully qualified names of the + alias and of the symbol it resolves to, as plain fields, without attributes, + indexes, conversions or format specs. + """ + + # One overload with `new_module` and one with only `new_name`, so a call with + # neither matches none of them. + @overload + def __init__( # noqa: D107 + self, + name: str, + /, + *, + new_module: str, + new_name: str | None = None, + since: str | None = None, + message: str | None = None, + ) -> None: ... + + @overload + def __init__( # noqa: D107 + self, + name: str, + /, + *, + new_module: None = None, + new_name: str, + since: str | None = None, + message: str | None = None, + ) -> None: ... + + def __init__( # noqa: DOC502 + self, + name: str, + /, + *, + new_module: str | None = None, + new_name: str | None = None, + since: str | None = None, + message: str | None = None, + ) -> None: + """Initialize this instance. + + At least one of `new_module` and `new_name` must be given. + + Args: + name: The deprecated name, in the module defining the alias. + new_module: The fully qualified name of the module the symbol lives in + now, if it moved out of the module defining the alias. + new_name: The name the symbol has now, if it was renamed. + since: The version the alias is deprecated since, such as `"v1.2.0"`, + for the documentation only. + message: The template for the warning message, replacing the standard + ` is deprecated. Use instead.`, formatted with `{old}` + and `{new}`, the fully qualified names of the alias and of the + symbol it resolves to, as plain fields, without attributes, + indexes, conversions or format specs. + + Raises: + TypeError: If an argument is not a string, or if neither `new_module` + nor `new_name` is given. + ValueError: If `name`, `new_name` or a part of `new_module` is not an + identifier, if `since` is empty, or if `message` is not a template + with only plain `{old}` and `{new}` fields. + """ + # The class is frozen, which blocks plain assignment here too. + object.__setattr__(self, "name", name) + object.__setattr__(self, "new_module", new_module) + object.__setattr__(self, "new_name", name if new_name is None else new_name) + object.__setattr__(self, "since", since) + object.__setattr__(self, "message", message) + self._validate(new_name) + + def _resolve(self, module: str) -> tuple[Any, str]: + """Look up the target before formatting the warning. + + Args: + module: The module that defines the alias. + + Returns: + The target object and the warning text. + + Raises: + TypeError: If the target is a module. + """ + new_module = module if self.new_module is None else self.new_module + new = f"{new_module}.{self.new_name}" + value = getattr(importlib.import_module(new_module), self.new_name) + if isinstance(value, ModuleType): + raise TypeError( + f"the target of {module}.{self.name} is the module {new}, and this " + "aliases names, not modules: the import system never consults a " + f"package's __getattr__, so `import {module}.{self.name}` would fail " + f"anyway. Keep a real __init__.py at {module}.{self.name}, with the " + "aliases for the names it used to hold in it." + ) + return value, self.format_message(old=f"{module}.{self.name}", new=new) + + def format_message(self, *, old: str, new: str) -> str: + """Format the warning message for this alias. + + Args: + old: The fully qualified name of the alias. + new: The fully qualified name of the symbol it resolves to. + + Returns: + The alias' `message` formatted with `old` and `new`, or + ` is deprecated. Use instead.` if it has none. + """ + if self.message is None: + return f"{old} is deprecated. Use {new} instead." + return self.message.format(old=old, new=new) + + def _validate(self, new_name: str | None) -> None: + """Check the fields. + + Args: + new_name: The `new_name` given to `__init__()`, before it defaulted to + `name`, to tell whether it was given at all. + + Raises: + TypeError: If neither `new_module` nor `new_name` is given. + """ + if self.new_module is None and new_name is None: + raise TypeError( + f"the alias {self.name!r} needs new_module, new_name or both, " + "got neither" + ) + _check_name("alias", self.name) + if self.new_module is not None: + _check_dotted_name( + self.name, "new_module", self.new_module, "a module name" + ) + self._validate_new_name() + _check_since(self.name, self.since) + _check_message(self.name, self.message, ("old", "new")) + + def _validate_new_name(self) -> None: + """Check that `new_name` is an identifier. + + Raises: + TypeError: If it is not a string. + ValueError: If it is not an identifier. + """ + if not isinstance(self.new_name, str): + raise TypeError( + f"the new_name of {self.name!r} must be a str, got {self.new_name!r}" + ) + if not self.new_name.isidentifier(): + raise ValueError( + f"the new_name of {self.name!r} is not an identifier: " + f"{self.new_name!r}" + ) + + +@dataclass(frozen=True, init=False, slots=True) +class DeprecatedSymbol: + """A deprecated module attribute and the value it still returns. + + Pass this entry to [`deprecated_symbols`][frequenz.core.warnings.deprecated_symbols] + to deprecate a constant, type variable or type alias. These cannot take the + [`typing_extensions.deprecated`][] decorator. If the same object is still + available under another name or in another module, use a + [`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias] instead. + + Declare the deprecated name only for type checkers. Python calls the module's + `__getattr__` only when an attribute is missing. It then returns `value`. + + The default warning is ` is deprecated. Use instead.` + Both names are fully qualified. Without a replacement, the warning is just + ` is deprecated.` In that case, provide a `message` that tells callers + what to do. + + Use `since` to record the version that deprecated the symbol. The runtime + warning does not include this version. Use `message` to customize the warning. + + To show a deprecation notice in your API docs, use + [`griffe-frequenz-core`](https://github.com/frequenz-floss/griffe-frequenz-core). + If the symbol has no `replacement`, write a `Deprecated:` notice in the + symbol’s docstring under `if TYPE_CHECKING:`. + + Everything is checked when the entry is created rather than when it is + reached. + """ + + name: str + """The deprecated name, in the module defining the symbol.""" + + value: Any + """The object returned when someone uses the deprecated name.""" + + replacement: str | None + """The fully qualified name of what to use instead, or `None` if there is none. + + It is only used in the messages: unlike a + [`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias], the symbol is not + the same object as its replacement. + """ + + since: str | None + """The version the symbol is deprecated since, or `None` if not given. + + It is only used for the documentation, never in the warning. + """ + + message: str | None + """The template for the warning message, or `None` for the standard one. + + It is formatted with `{old}`, the fully qualified name of the symbol, and + `{new}`, its [`replacement`][frequenz.core.warnings.DeprecatedSymbol.replacement] + if it has one, as plain fields, without attributes, indexes, conversions or + format specs. + """ + + def __init__( # noqa: DOC502 + self, + name: str, + /, + *, + value: Any, + replacement: str | None = None, + since: str | None = None, + message: str | None = None, + ) -> None: + """Initialize this instance. + + Args: + name: The deprecated name, in the module defining the symbol. + value: The object the deprecated name gives. + replacement: The fully qualified name of what to use instead, if there + is something. + since: The version the symbol is deprecated since, such as `"v1.2.0"`, + for the documentation only. + message: The template for the warning message, replacing the standard + one, formatted with `{old}`, the fully qualified name of the + symbol, and `{new}`, its `replacement` if it has one, as plain + fields, without attributes, indexes, conversions or format specs. + + Raises: + TypeError: If an argument is not a string. + ValueError: If `name` or a part of `replacement` is not an identifier, + if `since` is empty, or if `message` is not a template with only a + plain `{old}` field, and a plain `{new}` one if there is a + `replacement`. + """ + # The class is frozen, which blocks plain assignment here too. + object.__setattr__(self, "name", name) + object.__setattr__(self, "value", value) + object.__setattr__(self, "replacement", replacement) + object.__setattr__(self, "since", since) + object.__setattr__(self, "message", message) + self._validate() + + def _resolve(self, module: str) -> tuple[Any, str]: + """Return the stored value and warning text. + + Args: + module: The module that defines the symbol. + + Returns: + The stored value and the warning text. + """ + return self.value, self.format_message(old=f"{module}.{self.name}") + + def format_message(self, *, old: str) -> str: + """Format the warning message for this symbol. + + Args: + old: The fully qualified name of the symbol. + + Returns: + The symbol's `message` formatted with `old` and its `replacement`, or + ` is deprecated. Use instead.` if it has no + `message`, or ` is deprecated.` if it has neither. + """ + if self.message is not None: + if self.replacement is None: + return self.message.format(old=old) + return self.message.format(old=old, new=self.replacement) + if self.replacement is None: + return f"{old} is deprecated." + return f"{old} is deprecated. Use {self.replacement} instead." + + def _validate(self) -> None: + """Check the fields.""" + _check_name("symbol", self.name) + if self.replacement is not None: + _check_dotted_name( + self.name, "replacement", self.replacement, "a fully qualified name" + ) + _check_since(self.name, self.since) + _check_message( + self.name, + self.message, + ("old",) if self.replacement is None else ("old", "new"), + ) + + +def deprecated_symbols( # noqa: DOC502 + module: str, + /, + *symbols: DeprecatedAlias | DeprecatedSymbol, + category: type[Warning] = DeprecationWarning, + stacklevel: int = 2, +) -> Callable[[str], Any]: + '''Build a module `__getattr__` that warns about deprecated symbols. + + Use this for module-level symbols that should keep working, but warn whoever + uses them, when a [`typing_extensions.deprecated`][] decorator is not an + option. There are two kinds, and a module can have both in the same call: + + - A [`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias] keeps the old + import path of a symbol that moved to another module, or was renamed. The + decorator is not an option because the object is not yours to mark: + decorating it would deprecate it for everybody, including the users of its + new home or name. The alias stays the very same object, so + [`isinstance`][] keeps working through both paths. + - A [`DeprecatedSymbol`][frequenz.core.warnings.DeprecatedSymbol] is a symbol + deprecated where it is, that the decorator can't mark because it is not a + class or a function, such as a type variable, a constant or a type alias. + + Each entry says since which version it is deprecated, so symbols deprecated in + different releases are documented with their own version, and can give their + own warning message. + + Danger: + Follow the usage example structure strictly. In particular never drop + the `else:`, otherwise a type checker will see the `__getattr__` + assignment and treat every symbol in the module as [`Any`][typing.Any], + effectively disabling type checking for the entire module. + + Warning: Star imports + A star import (`from module import *`) only consults `__getattr__` for + the names listed in the module's `__all__`. Without an `__all__`, it + takes only the names the module defines itself, so the deprecated symbols + silently disappear from star imports, and code using them fails with a + [`NameError`][] instead of getting the deprecation warning. Keep every + deprecated symbol in `__all__` until it is removed. + + Example: Usage + This is how a module that used to define `Decimal` itself, and now gets it + from [`decimal`][], keeps the old import path working: + + ```python + from typing import TYPE_CHECKING, TypeAlias + + from frequenz.core.warnings import DeprecatedAlias, deprecated_symbols + + __all__ = ["Decimal"] # Keeps the alias in star imports + + if TYPE_CHECKING: + # Private import, only for type checkers + from decimal import Decimal as _Decimal + + Decimal: TypeAlias = _Decimal + else: + __getattr__ = deprecated_symbols( + __name__, + DeprecatedAlias("Decimal", new_module="decimal", since="v1.2.0"), + ) + ``` + + Reaching `Decimal` through this module, say `mypkg.Decimal`, now emits a + `DeprecationWarning` saying `mypkg.Decimal is deprecated. Use + decimal.Decimal instead.` + + `since` doesn't change the warning: it is for + [`griffe-frequenz-core`](https://github.com/frequenz-floss/griffe-frequenz-core), + which documents the alias with a ``Deprecated since v1.2.0. Use + [`decimal.Decimal`][] instead.`` notice. + + Example: Renaming + When the symbol was also renamed on the way out, `new_name` gives the name + it has now: + + ```python + from typing import TYPE_CHECKING, TypeAlias + + from frequenz.core.warnings import DeprecatedAlias, deprecated_symbols + + if TYPE_CHECKING: + from fractions import Fraction as _Fraction + + Rational: TypeAlias = _Fraction + else: + __getattr__ = deprecated_symbols( + __name__, + DeprecatedAlias( + "Rational", + new_module="fractions", + new_name="Fraction", + since="v1.3.0", + ), + ) + ``` + + Without `new_module`, the symbol was renamed in this very module: + + ```python + from typing import TYPE_CHECKING, TypeAlias + + from frequenz.core.warnings import DeprecatedAlias, deprecated_symbols + + + class Widget: + ... # Called Gadget before v1.4.0 + + + if TYPE_CHECKING: + Gadget: TypeAlias = Widget + else: + __getattr__ = deprecated_symbols( + __name__, + DeprecatedAlias("Gadget", new_name="Widget", since="v1.4.0"), + ) + ``` + + Example: Custom message + When the standard warning is not enough, an alias can give its own + message, as a template that gets the fully qualified old and new names as + `{old}` and `{new}`: + + ```python + from typing import TYPE_CHECKING, TypeAlias + + from frequenz.core.warnings import DeprecatedAlias, deprecated_symbols + + if TYPE_CHECKING: + from decimal import Decimal as _Decimal + + Decimal: TypeAlias = _Decimal + else: + __getattr__ = deprecated_symbols( + __name__, + DeprecatedAlias( + "Decimal", + new_module="decimal", + since="v1.2.0", + message="{old} is deprecated and will be removed in v2.0.0. " + "Use {new} instead.", + ), + ) + ``` + + The message replaces the warning only: the notice is still generated from + `since` and where the symbol is now. To say more in the documentation too, + write a `Deprecated:` admonition by hand in the docstring of `Decimal` in + the `if TYPE_CHECKING:` branch, which replaces the generated notice. + + Example: Deprecating in place + A symbol that is not moving, but is replaced by something else, such as a + constant in seconds replaced by a [`timedelta`][datetime.timedelta], is a + [`DeprecatedSymbol`][frequenz.core.warnings.DeprecatedSymbol]. The + `__getattr__` is only called for names the module doesn't have, so the + value is kept under a private name, given to the entry as `value`, and the + public name is only declared for type checkers: + + ```python + from datetime import timedelta + from typing import TYPE_CHECKING, Final + + from frequenz.core.warnings import DeprecatedSymbol, deprecated_symbols + + __all__ = ["TIMEOUT", "TIMEOUT_SECONDS"] + + TIMEOUT: Final = timedelta(seconds=30) + """How long to wait for a reply.""" + + _TIMEOUT_SECONDS: Final = 30.0 + + if TYPE_CHECKING: + TIMEOUT_SECONDS: Final = _TIMEOUT_SECONDS + """How long to wait for a reply, in seconds.""" + else: + __getattr__ = deprecated_symbols( + __name__, + DeprecatedSymbol( + "TIMEOUT_SECONDS", + value=_TIMEOUT_SECONDS, + replacement="mypkg.TIMEOUT", + since="v1.5.0", + ), + ) + ``` + + Reaching `mypkg.TIMEOUT_SECONDS` now gives `30.0` and emits a + `DeprecationWarning` saying `mypkg.TIMEOUT_SECONDS is deprecated. Use + mypkg.TIMEOUT instead.` `replacement` is a fully qualified name, used only + in the messages, since `TIMEOUT` is not the same object. + + Without a `replacement`, the symbol is just going away. The warning would + only say ` is deprecated.`, so give a `message` saying what to do + instead, and write the notice by hand: + + ```python + from typing import TYPE_CHECKING, TypeVar + + from frequenz.core.warnings import DeprecatedSymbol, deprecated_symbols + + __all__ = ["ValueT"] + + if TYPE_CHECKING: + ValueT = TypeVar("ValueT") + """A type variable for values. + + Deprecated: + Deprecated since v1.6.0. Define your own type variable instead. + """ + else: + __getattr__ = deprecated_symbols( + __name__, + DeprecatedSymbol( + "ValueT", + value=TypeVar("ValueT"), + since="v1.6.0", + message="{old} is deprecated and will be removed in v2.0.0. " + "Define your own type variable instead.", + ), + ) + ``` + + Tip: Deprecating whole modules + This function can't be used to deprecate a whole module. If you need to + do that, you can keep a real `__init__.py` at the old path, with a + `__getattr__ = deprecated_symbols(...)` that includes all the symbols + that used to be reachable there. + + Warning: Security Warning + This function imports the modules the aliases point at, so the aliases are + as trusted as an `import` statement in this module. Write them out as + literals; don't build them from anything that comes from outside the + program. + + Args: + module: The fully qualified name of the module defining the symbols. + *symbols: The deprecated symbols, at least one, each with its own name. + category: The category of the warning to emit. + stacklevel: How far up the stack the warning is reported, counting from the + `__getattr__` itself. The default of 2 points at the code reaching for + the symbol, and only needs raising if something wraps the returned + function. + + Returns: + A function suitable for use as the module's `__getattr__`. + + Raises: + TypeError: If an argument has the wrong type, including an entry that is + neither a [`DeprecatedAlias`][frequenz.core.warnings.DeprecatedAlias] + nor a [`DeprecatedSymbol`][frequenz.core.warnings.DeprecatedSymbol], or + a `DeprecatedSymbol` whose value is a module. Also later, when an alias + is reached, if it resolves to a module rather than to a symbol in one. + ValueError: If there are no symbols, if two of them have the same name, if + an alias points at a deprecated symbol in the same module, itself + included, or if `stacklevel` is smaller than 1. + ''' + if not isinstance(module, str): + raise TypeError(f"module must be a str, got {module!r}") + if not (isinstance(category, type) and issubclass(category, Warning)): + raise TypeError(f"category must be a Warning subclass, got {category!r}") + if not isinstance(stacklevel, int): + raise TypeError(f"stacklevel must be an int, got {stacklevel!r}") + if stacklevel < 1: + raise ValueError(f"stacklevel must be 1 or more, got {stacklevel!r}") + by_name = _checked_symbols(module, symbols) + + def module_getattr(name: str) -> Any: # noqa: DOC503 + """Return a deprecated symbol, warning about it. + + Args: + name: The name being looked up in the module. + + Returns: + The object the deprecated symbol gives. + + Raises: + AttributeError: If the name is not one of the deprecated symbols. + TypeError: If an alias resolves to a module, which this can't keep + reachable from its old path. + """ + entry = by_name.get(name) + if entry is None: + raise AttributeError(f"module {module!r} has no attribute {name!r}") + value, message = entry._resolve(module) # pylint: disable=protected-access + warnings.warn(message, category, stacklevel=stacklevel) + return value + + return module_getattr + + +def _checked_symbols( + module: str, symbols: tuple[DeprecatedAlias | DeprecatedSymbol, ...] +) -> dict[str, DeprecatedAlias | DeprecatedSymbol]: + """Check the entries given to `deprecated_symbols()` as a whole. + + Each entry checks its own fields when it is created; this checks what only + the whole table can tell. + + Args: + module: The fully qualified name of the module defining the symbols. + symbols: The entries. + + Returns: + The entries by name. + + Raises: + TypeError: If an entry is neither a `DeprecatedAlias` nor a + `DeprecatedSymbol`, or if a `DeprecatedSymbol`'s value is a module. + ValueError: If there are no entries, if two of them have the same name, or + if an alias points at a deprecated symbol in the same module. + """ + if not symbols: + raise ValueError(f"no deprecated symbols given for module {module!r}") + by_name: dict[str, DeprecatedAlias | DeprecatedSymbol] = {} + for entry in symbols: + # Also what a mapping, the form `deprecated_aliases()` used to take, runs + # into. + if not isinstance(entry, (DeprecatedAlias, DeprecatedSymbol)): + raise TypeError( + "deprecated symbols must be DeprecatedAlias or DeprecatedSymbol " + f"instances, got {entry!r}" + ) + # A dict literal would keep the last of two entries silently; this is the + # one place that can tell. + if entry.name in by_name: + raise ValueError(f"the symbol {entry.name!r} is given more than once") + if isinstance(entry, DeprecatedSymbol) and isinstance(entry.value, ModuleType): + raise TypeError( + f"the value of {module}.{entry.name} is the module " + f"{entry.value.__name__}, and this deprecates names, not modules: " + "the import system never consults a package's __getattr__, so " + f"`import {module}.{entry.name}` would fail anyway. Keep a real " + f"__init__.py at {module}.{entry.name}, with the deprecated names " + "it used to hold in it." + ) + by_name[entry.name] = entry + for entry in symbols: + # Reaching it would call this `__getattr__` again, and never stop if the + # aliases point at each other. Pointing at a `DeprecatedSymbol` wouldn't + # loop, but would warn twice and send users to something deprecated too. + if ( + isinstance(entry, DeprecatedAlias) + and entry.new_module in (None, module) + and entry.new_name in by_name + ): + raise ValueError( + f"the alias {entry.name!r} points at {module}.{entry.new_name}, " + "which is deprecated too" + ) + return by_name + + +@deprecated( + "frequenz.core.warnings.deprecated_aliases is deprecated. " + "Use frequenz.core.warnings.deprecated_symbols instead." +) +def deprecated_aliases( # noqa: DOC502 + module: str, + /, + *aliases: DeprecatedAlias, + category: type[Warning] = DeprecationWarning, + stacklevel: int = 2, +) -> Callable[[str], Any]: + """Build a module `__getattr__` that warns about deprecated aliases. + + Deprecated: + Deprecated since v1.7.0. Use + [`deprecated_symbols`][frequenz.core.warnings.deprecated_symbols] + with the same arguments. The old function will be removed in v2.0.0. + + Args: + module: The fully qualified name of the module defining the aliases. + *aliases: The deprecated aliases, at least one, each with its own name. + category: The category of the warning to emit. + stacklevel: How far up the stack the warning is reported, counting from the + `__getattr__` itself. + + Returns: + A function suitable for use as the module's `__getattr__`. + + Raises: + TypeError: If an argument has the wrong type. + ValueError: If the aliases are not valid together, or if `stacklevel` is + smaller than 1. + """ + return deprecated_symbols( + module, *aliases, category=category, stacklevel=stacklevel + ) + + +def _check_name(kind: str, name: object) -> None: + """Check that the entry has a valid Python identifier. + + Args: + kind: The entry type to show in error messages. + name: The name to check. + + Raises: + TypeError: If it is not a string. + ValueError: If it is not an identifier. + """ + if not isinstance(name, str): + raise TypeError(f"{kind} names must be str, got {name!r}") + if not name.isidentifier(): + raise ValueError(f"{kind} names must be identifiers, got {name!r}") + + +def _check_dotted_name(name: str, field: str, value: object, what: str) -> None: + """Check that each part of a dotted name is an identifier. + + Args: + name: The name of the entry, for the error messages. + field: The name of the field, for the error messages. + value: The value of the field. + what: What the field should be, for the error messages. + + Raises: + TypeError: If it is not a string. + ValueError: If one of its dotted parts is not an identifier. + """ + if not isinstance(value, str): + raise TypeError(f"the {field} of {name!r} must be a str, got {value!r}") + if not all(part.isidentifier() for part in value.split(".")): + raise ValueError(f"the {field} of {name!r} is not {what}: {value!r}") + + +def _check_since(name: str, since: object) -> None: + """Check that `since` is a nonempty string or `None`. + + Args: + name: The name of the entry, for the error messages. + since: The `since` to check. + + Raises: + TypeError: If it is not a string. + ValueError: If it is empty or blank. + """ + if since is None: + return + if not isinstance(since, str): + raise TypeError(f"the since of {name!r} must be a str, got {since!r}") + if not since.strip(): + raise ValueError(f"the since of {name!r} is empty") + + +def _check_message(name: str, message: object, fields: tuple[str, ...]) -> None: + """Check that a warning template uses only the allowed plain fields. + + Args: + name: The name of the entry, for the error messages. + message: The `message` to check. + fields: The names of the fields it may use. + + Raises: + TypeError: If it is not a string. + ValueError: If it has a stray brace, or a replacement field other than one + of `fields`, plain. + """ + if message is None: + return + if not isinstance(message, str): + raise TypeError(f"the message of {name!r} must be a str, got {message!r}") + allowed = " and ".join(f"{{{field}}}" for field in fields) + problem = ( + f"the message of {name!r} must be a template with only plain {allowed} " + f"fields, got {message!r}" + ) + try: + # A stray brace raises here. + parsed = list(string.Formatter().parse(message)) + except ValueError as error: + raise ValueError(problem) from error + # Anything more than a plain field can fail depending on the names it is + # formatted with, which are only known when the entry is reached, so + # formatting it once here can't tell: `{old.missing}` raises + # `AttributeError`, and `{old:{new}}` makes the new name a format spec. + if not all( + (field is None or field in fields) and not spec and conversion is None + for _, field, spec, conversion in parsed + ): + raise ValueError(problem) diff --git a/tests/__init__.py b/tests/__init__.py index b15f429..a919476 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -4,5 +4,5 @@ """Tests for the frequenz-core library. This is a package so the helper packages the tests import, like -`tests.warnings.documented_aliases`, have the same name for pytest and for mypy. +`tests.warnings.documented_symbols`, have the same name for pytest and for mypy. """ diff --git a/tests/warnings/documented_aliases/__init__.py b/tests/warnings/documented_symbols/__init__.py similarity index 52% rename from tests/warnings/documented_aliases/__init__.py rename to tests/warnings/documented_symbols/__init__.py index 43354ec..8bb653c 100644 --- a/tests/warnings/documented_aliases/__init__.py +++ b/tests/warnings/documented_symbols/__init__.py @@ -1,20 +1,26 @@ # License: MIT # Copyright © 2026 Frequenz Energy-as-a-Service GmbH -"""A package written the way `deprecated_aliases()` documents, for the tests. +"""A package written the way `deprecated_symbols()` documents, for the tests. The other tests build a `ModuleType` and assign the `__getattr__` onto it, which exercises the function but not the shape the docstring tells people to write: the -aliases declared under `if TYPE_CHECKING:`, the assignment in the `else:` branch, +symbols declared under `if TYPE_CHECKING:`, the assignment in the `else:` branch, and a real module the import system loads. This package is that shape, so the tests importing from here fail if the documented pattern stops working. """ -from typing import TYPE_CHECKING, TypeAlias +from datetime import timedelta +from typing import TYPE_CHECKING, Final, TypeAlias, TypeVar -from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases +from frequenz.core.warnings import DeprecatedAlias, DeprecatedSymbol, deprecated_symbols -__all__ = ["Decimal", "Rational", "kept"] +__all__ = ["TIMEOUT", "TIMEOUT_SECONDS", "Decimal", "Rational", "ValueT", "kept"] + +TIMEOUT: Final = timedelta(seconds=30) +"""How long to wait for a reply.""" + +_TIMEOUT_SECONDS: Final = 30.0 if TYPE_CHECKING: # Only for type checkers, which can't see the runtime `__getattr__` in the @@ -32,8 +38,18 @@ Deprecated since v1.3.0, and will be removed in v2.0.0. Use [`fractions.Fraction`][] instead. """ + + TIMEOUT_SECONDS: Final = _TIMEOUT_SECONDS + """How long to wait for a reply, in seconds.""" + + ValueT = TypeVar("ValueT") + """A type variable for values. + + Deprecated: + Deprecated since v1.6.0. Define your own type variable instead. + """ else: - __getattr__ = deprecated_aliases( + __getattr__ = deprecated_symbols( __name__, DeprecatedAlias("Decimal", new_module="decimal", since="v1.2.0"), DeprecatedAlias( @@ -44,6 +60,19 @@ message="{old} is deprecated and will be removed in v2.0.0. " "Use {new} instead.", ), + DeprecatedSymbol( + "TIMEOUT_SECONDS", + value=_TIMEOUT_SECONDS, + replacement="tests.warnings.documented_symbols.TIMEOUT", + since="v1.5.0", + ), + DeprecatedSymbol( + "ValueT", + value=TypeVar("ValueT"), + since="v1.6.0", + message="{old} is deprecated and will be removed in v2.0.0. " + "Define your own type variable instead.", + ), ) diff --git a/tests/warnings/test_deprecated_aliases.py b/tests/warnings/test_deprecated_symbols.py similarity index 60% rename from tests/warnings/test_deprecated_aliases.py rename to tests/warnings/test_deprecated_symbols.py index e6ee863..f9b6c47 100644 --- a/tests/warnings/test_deprecated_aliases.py +++ b/tests/warnings/test_deprecated_symbols.py @@ -1,24 +1,26 @@ # License: MIT # Copyright © 2026 Frequenz Energy-as-a-Service GmbH -"""Tests for `deprecated_aliases()`.""" +"""Tests for `deprecated_symbols()`.""" import dataclasses import decimal import fractions import sys from types import ModuleType -from typing import Any +from typing import Any, TypeVar import pytest +from frequenz.core import warnings as core_warnings from frequenz.core.warnings import ( DeprecatedAlias, - _deprecated_aliases, + DeprecatedSymbol, + _deprecated_symbols, asserting_no_deprecations, - deprecated_aliases, + deprecated_symbols, ) -from tests.warnings import documented_aliases +from tests.warnings import documented_symbols _MESSAGE = "{old} is deprecated and will be removed. Use {new} instead." @@ -211,6 +213,146 @@ def test_deprecated_alias_formats_its_message() -> None: ) +_SENTINEL = object() + + +def test_deprecated_symbol_keeps_what_it_was_given() -> None: + """Test that a symbol keeps its fields as given, and can't be changed.""" + symbol = DeprecatedSymbol( + "OLD", + value=_SENTINEL, + replacement="mypkg.NEW", + since="v1.2.3", + message=_MESSAGE, + ) + + assert symbol.name == "OLD" + assert symbol.value is _SENTINEL + assert symbol.replacement == "mypkg.NEW" + assert symbol.since == "v1.2.3" + assert symbol.message == _MESSAGE + assert symbol == DeprecatedSymbol( + "OLD", + value=_SENTINEL, + replacement="mypkg.NEW", + since="v1.2.3", + message=_MESSAGE, + ) + with pytest.raises(dataclasses.FrozenInstanceError): + symbol.value = None # type: ignore[misc] + + bare = DeprecatedSymbol("OLD", value=None) + assert bare.value is None + assert bare.replacement is None + assert bare.since is None + assert bare.message is None + + +@pytest.mark.parametrize( + "args, kwargs", + [ + (("OLD", 1), {}), + ((), {"name": "OLD", "value": 1}), + (("OLD",), {}), + (("OLD", 1, "mypkg.NEW"), {}), + ], + ids=["value-positional", "name-by-keyword", "no-value", "replacement-positional"], +) +def test_deprecated_symbol_signature( + args: tuple[Any, ...], kwargs: dict[str, Any] +) -> None: + """Test that the name is positional-only, and the rest keyword-only.""" + with pytest.raises(TypeError): + DeprecatedSymbol(*args, **kwargs) + + +@pytest.mark.parametrize( + "name, replacement, since, message, error", + [ + (0, None, None, None, TypeError), + ("", None, None, None, ValueError), + ("O LD", None, None, None, ValueError), + ("OLD", 0, None, None, TypeError), + ("OLD", "", None, None, ValueError), + ("OLD", "mypkg..NEW", None, None, ValueError), + ("OLD", "mypkg.NEW-2", None, None, ValueError), + ("OLD", None, 0, None, TypeError), + ("OLD", None, " ", None, ValueError), + ("OLD", None, None, 0, TypeError), + ("OLD", None, None, "{old} is gone, see {'here': 1}", ValueError), + ("OLD", None, None, "{old} is gone, use {new}", ValueError), + ("OLD", "mypkg.NEW", None, "{old} is gone, use {where}", ValueError), + ("OLD", "mypkg.NEW", None, "{} is gone, use {new}", ValueError), + ("OLD", "mypkg.NEW", None, "{old.missing} is gone", ValueError), + ("OLD", "mypkg.NEW", None, "{old!r} is gone", ValueError), + ("OLD", "mypkg.NEW", None, "{old:>20} is gone", ValueError), + ], + ids=[ + "name-type", + "name-empty", + "name-not-identifier", + "replacement-type", + "replacement-empty", + "replacement-empty-part", + "replacement-not-identifier", + "since-type", + "since-blank", + "message-type", + "message-stray-brace", + "message-new-without-replacement", + "message-unknown-field", + "message-auto-numbered-field", + "message-attribute", + "message-conversion", + "message-format-spec", + ], +) +def test_deprecated_symbol_rejects_bad_arguments( + name: Any, + replacement: Any, + since: Any, + message: Any, + error: type[Exception], +) -> None: + """Test that a symbol is checked when it is created, like an alias. + + `{new}` is only there to stand for the replacement, so a symbol without one + can't use it. + """ + with pytest.raises(error): + DeprecatedSymbol( + name, value=1, replacement=replacement, since=since, message=message + ) + + +def test_deprecated_symbol_formats_its_message() -> None: + """Test the standard messages, with and without a replacement, and `message`. + + `since` never shows up in any: it is only for the documentation. + """ + old = "mypkg.OLD" + + bare = DeprecatedSymbol("OLD", value=1, since="v{1}.2") + assert bare.format_message(old=old) == "mypkg.OLD is deprecated." + + replaced = DeprecatedSymbol("OLD", value=1, replacement="mypkg.NEW") + assert replaced.format_message(old=old) == ( + "mypkg.OLD is deprecated. Use mypkg.NEW instead." + ) + + message = DeprecatedSymbol( + "OLD", value=1, message="{old} is gone ({{v2}}), do it yourself" + ) + assert message.format_message(old=old) == ( + "mypkg.OLD is gone ({v2}), do it yourself" + ) + + both = DeprecatedSymbol( + "OLD", value=1, replacement="mypkg.NEW", message="{old} is gone, see {new}" + ) + assert both.format_message(old=old) == "mypkg.OLD is gone, see mypkg.NEW" + + _DECIMAL = DeprecatedAlias("Decimal", new_module="decimal", since="v1.2.3") @@ -221,7 +363,7 @@ def test_deprecated_aliases_warns_and_returns_the_real_object() -> None: wording; `Fraction` gives a message of its own. """ module = ModuleType("old_home") - module.__getattr__ = deprecated_aliases( # type: ignore[method-assign] + module.__getattr__ = deprecated_symbols( # type: ignore[method-assign] module.__name__, _DECIMAL, DeprecatedAlias( @@ -246,7 +388,7 @@ def test_deprecated_aliases_warns_and_returns_the_real_object() -> None: def test_deprecated_aliases_rejects_unknown_names() -> None: """Test that a name that is not an alias raises as a missing attribute would.""" module = ModuleType("old_home_missing") - module.__getattr__ = deprecated_aliases( # type: ignore[method-assign] + module.__getattr__ = deprecated_symbols( # type: ignore[method-assign] module.__name__, _DECIMAL ) @@ -326,13 +468,13 @@ def test_deprecated_aliases_rejects_a_bad_table( point at each other. """ with pytest.raises(error): - deprecated_aliases(*args, **kwargs) + deprecated_symbols(*args, **kwargs) def test_deprecated_aliases_follows_renames() -> None: """Test that an alias can point to a symbol with a different name.""" module = ModuleType("old_home_renamed") - module.__getattr__ = deprecated_aliases( # type: ignore[method-assign] + module.__getattr__ = deprecated_symbols( # type: ignore[method-assign] module.__name__, DeprecatedAlias( "Rational", new_module="fractions", new_name="Fraction", message=_MESSAGE @@ -359,7 +501,7 @@ def test_deprecated_aliases_follows_renames_in_place( """ module = ModuleType("old_home_in_place") module.Widget = fractions.Fraction # type: ignore[attr-defined] - module.__getattr__ = deprecated_aliases( # type: ignore[method-assign] + module.__getattr__ = deprecated_symbols( # type: ignore[method-assign] module.__name__, DeprecatedAlias("Gadget", new_name="Widget", since="v1.2.3"), ) @@ -378,7 +520,7 @@ def test_deprecated_aliases_follows_renames_in_place( def test_deprecated_aliases_customises_the_warning() -> None: """Test the category and stacklevel overrides.""" module = ModuleType("old_home_custom") - module.__getattr__ = deprecated_aliases( # type: ignore[method-assign] + module.__getattr__ = deprecated_symbols( # type: ignore[method-assign] module.__name__, _DECIMAL, category=FutureWarning, @@ -392,7 +534,7 @@ def test_deprecated_aliases_customises_the_warning() -> None: assert module.Decimal is decimal.Decimal # stacklevel=1, so the warning is attributed to the helper itself. - assert caught[0].filename == _deprecated_aliases.__file__ + assert caught[0].filename == _deprecated_symbols.__file__ @pytest.mark.parametrize( @@ -413,7 +555,7 @@ def test_deprecated_aliases_rejects_bad_customisation( ) -> None: """Test that the overrides are checked when the aliases are declared.""" with pytest.raises(error): - deprecated_aliases("old_home_bad", _DECIMAL, **kwargs) + deprecated_symbols("old_home_bad", _DECIMAL, **kwargs) def test_deprecated_aliases_in_a_real_module() -> None: @@ -428,35 +570,54 @@ def test_deprecated_aliases_in_a_real_module() -> None: with pytest.warns( DeprecationWarning, match=( - "^tests.warnings.documented_aliases.Decimal is deprecated. " + "^tests.warnings.documented_symbols.Decimal is deprecated. " "Use decimal.Decimal instead.$" ), ): - assert documented_aliases.Decimal is decimal.Decimal + assert documented_symbols.Decimal is decimal.Decimal with pytest.warns( DeprecationWarning, match=( - "^tests.warnings.documented_aliases.Rational is deprecated and will be " + "^tests.warnings.documented_symbols.Rational is deprecated and will be " "removed in v2.0.0. Use fractions.Fraction instead.$" ), ): - assert documented_aliases.Rational is fractions.Fraction + assert documented_symbols.Rational is fractions.Fraction + + with pytest.warns( + DeprecationWarning, + match=( + "^tests.warnings.documented_symbols.TIMEOUT_SECONDS is deprecated. " + "Use tests.warnings.documented_symbols.TIMEOUT instead.$" + ), + ): + assert documented_symbols.TIMEOUT_SECONDS == 30.0 + + with pytest.warns( + DeprecationWarning, + match=( + "^tests.warnings.documented_symbols.ValueT is deprecated and will be " + "removed in v2.0.0. Define your own type variable instead.$" + ), + ): + assert isinstance(documented_symbols.ValueT, TypeVar) # What the package defines itself is untouched: the `__getattr__` is only # consulted for names the module doesn't have. with asserting_no_deprecations(): - assert documented_aliases.kept() == "kept" + assert documented_symbols.kept() == "kept" + assert documented_symbols.TIMEOUT.total_seconds() == 30.0 with pytest.raises( AttributeError, - match="module 'tests.warnings.documented_aliases' has no attribute 'Nope'", + match="module 'tests.warnings.documented_symbols' has no attribute 'Nope'", ): # The `type: ignore` is the point of the `else:` branch, not a nuisance: # with the `__getattr__` at module level mypy would type this `Any` and # say nothing, here and in every downstream import of a name that never # existed. - _ = documented_aliases.Nope # type: ignore[attr-defined] + _ = documented_symbols.Nope # type: ignore[attr-defined] def test_deprecated_aliases_reach_star_imports() -> None: @@ -470,21 +631,35 @@ def test_deprecated_aliases_reach_star_imports() -> None: with pytest.warns(DeprecationWarning) as caught: # pylint: disable-next=exec-used - exec("from tests.warnings.documented_aliases import *", namespace) + exec("from tests.warnings.documented_symbols import *", namespace) - assert documented_aliases.__all__ == ["Decimal", "Rational", "kept"] + assert documented_symbols.__all__ == [ + "TIMEOUT", + "TIMEOUT_SECONDS", + "Decimal", + "Rational", + "ValueT", + "kept", + ] assert namespace["Decimal"] is decimal.Decimal assert namespace["Rational"] is fractions.Fraction - assert namespace["kept"] is documented_aliases.kept + assert namespace["TIMEOUT_SECONDS"] == 30.0 + assert isinstance(namespace["ValueT"], TypeVar) + assert namespace["TIMEOUT"] is documented_symbols.TIMEOUT + assert namespace["kept"] is documented_symbols.kept # Each name in a package's `__all__` is asked for twice, once by the import # machinery finding out whether it names a submodule and once by the wildcard - # import itself, so every alias warns more than once here. Which messages come + # import itself, so every symbol warns more than once here. Which messages come # out is the part worth asserting; how many times CPython looks them up is not. assert {str(warning.message) for warning in caught} == { - "tests.warnings.documented_aliases.Decimal is deprecated. " + "tests.warnings.documented_symbols.Decimal is deprecated. " "Use decimal.Decimal instead.", - "tests.warnings.documented_aliases.Rational is deprecated and will be " + "tests.warnings.documented_symbols.Rational is deprecated and will be " "removed in v2.0.0. Use fractions.Fraction instead.", + "tests.warnings.documented_symbols.TIMEOUT_SECONDS is deprecated. " + "Use tests.warnings.documented_symbols.TIMEOUT instead.", + "tests.warnings.documented_symbols.ValueT is deprecated and will be " + "removed in v2.0.0. Define your own type variable instead.", } @@ -498,7 +673,7 @@ def test_deprecated_aliases_refuses_a_module_target() -> None: path. """ module = ModuleType("old_home_package") - module.__getattr__ = deprecated_aliases( # type: ignore[method-assign] + module.__getattr__ = deprecated_symbols( # type: ignore[method-assign] module.__name__, # os.path is a module DeprecatedAlias("path", new_module="os", message=_MESSAGE), @@ -512,3 +687,113 @@ def test_deprecated_aliases_refuses_a_module_target() -> None: with asserting_no_deprecations(): with pytest.raises(TypeError): _ = module.path + + +def test_deprecated_symbols_warns_and_returns_the_value() -> None: + """Test that reaching a symbol warns and gives its value, next to aliases.""" + module = ModuleType("old_home_symbols") + module.__getattr__ = deprecated_symbols( # type: ignore[method-assign] + module.__name__, + _DECIMAL, + DeprecatedSymbol("OLD", value=_SENTINEL, replacement="mypkg.NEW"), + DeprecatedSymbol("GONE", value=None, since="v1.2.3"), + DeprecatedSymbol( + "SAID", value=3, message="{old} is deprecated. Count by hand instead." + ), + ) + + with pytest.warns(DeprecationWarning) as caught: + assert module.OLD is _SENTINEL + assert module.GONE is None + assert module.SAID == 3 + assert module.Decimal is decimal.Decimal + + assert [str(warning.message) for warning in caught] == [ + "old_home_symbols.OLD is deprecated. Use mypkg.NEW instead.", + "old_home_symbols.GONE is deprecated.", + "old_home_symbols.SAID is deprecated. Count by hand instead.", + "old_home_symbols.Decimal is deprecated. Use decimal.Decimal instead.", + ] + # stacklevel=2, so the warning is attributed to this file, not to the helper. + assert all(warning.filename == __file__ for warning in caught) + + +@pytest.mark.parametrize( + "symbols", + [ + ( + DeprecatedSymbol("Decimal", value=1), + _DECIMAL, + ), + ( + DeprecatedSymbol("OLD", value=1), + DeprecatedAlias("Older", new_name="OLD", since="v1.2.3"), + ), + ( + DeprecatedSymbol("OLD", value=1), + DeprecatedAlias( + "Older", new_module="old_home_bad", new_name="OLD", since="v1.2.3" + ), + ), + ], + ids=[ + "duplicate-name", + "alias-points-at-a-symbol", + "alias-points-at-a-symbol-by-module", + ], +) +def test_deprecated_symbols_rejects_a_bad_mix( + symbols: tuple[DeprecatedAlias | DeprecatedSymbol, ...], +) -> None: + """Test that aliases and symbols are checked together. + + They share the module's names, so they can't repeat one, and an alias pointing + at a deprecated symbol would warn twice and send users to something deprecated + too. + """ + with pytest.raises(ValueError): + deprecated_symbols("old_home_bad", *symbols) + + +def test_deprecated_symbols_refuses_a_module_value() -> None: + """Test that a symbol whose value is a module is refused when it is declared. + + As for an alias landing on a module, `import old.sub` would still fail, since + the import system never asks a package's `__getattr__`. + """ + with pytest.raises(TypeError, match="^the value of old_home_bad.path is the "): + deprecated_symbols( + "old_home_bad", + DeprecatedSymbol("path", value=sys.modules["os.path"], message="{old}"), + ) + + +def test_deprecated_aliases_is_a_deprecated_name_for_deprecated_symbols() -> None: + """Test that the old name still builds the same `__getattr__`, warning once. + + It warns when it is called, which is when the module defining the aliases is + imported, and the `__getattr__` it returns warns about each alias as usual. + """ + module = ModuleType("old_home_old_name") + with pytest.deprecated_call( + match=( + "^frequenz.core.warnings.deprecated_aliases is deprecated. " + "Use frequenz.core.warnings.deprecated_symbols instead.$" + ) + ) as caught: + module.__getattr__ = core_warnings.deprecated_aliases( # type: ignore[method-assign] + module.__name__, _DECIMAL + ) + + assert len(caught) == 1 + # The call is reported, not the wrapper. + assert caught[0].filename == __file__ + + with pytest.warns( + DeprecationWarning, + match="^old_home_old_name.Decimal is deprecated. Use decimal.Decimal instead.$", + ) as caught: + assert module.Decimal is decimal.Decimal + + # The default stacklevel still points at the code reaching for the alias. + assert caught[0].filename == __file__