Griffe Extensions for frequenz-core¤
Introduction¤
This package provides Griffe
extensions that help mkdocstrings understand
some helpers from
frequenz-core.
Some of these helpers use patterns that Griffe can't fully understand by just reading the source code. This means that some information might be missing from the generated API documentation.
The extensions fill in these gaps. The first one handles deprecations:
frequenz-core can deprecate APIs using function calls instead of decorators.
This package documents both these calls and the @deprecated decorator. It
replaces
griffe-warnings-deprecated.
The extensions recognize helpers by their fully qualified names, without
importing frequenz-core. So you don't need frequenz-core as a dependency,
and you can use the extensions to document any project that uses these helpers.
Installation¤
Add griffe-frequenz-core to your documentation dependencies, alongside
mkdocstrings.
Then enable the extensions you want in the extensions option of the
mkdocstrings Python handler, as shown below.
Documenting deprecations¤
The griffe_frequenz_core.deprecations extension finds deprecations made using
@deprecated and frequenz-core helper functions. Enable it like this:
Don't enable it alongside griffe-warnings-deprecated. See Switching from
griffe-warnings-deprecated for how
to update your configuration.
For each deprecated object, the extension:
- Adds a
deprecatedlabel. - Stores the deprecation notice in the object's
deprecatedfield. - Adds an admonition with the notice at the top of its docstring.
The notices follow the deprecations guide.
A warning shown at runtime is different from a notice in the documentation. The runtime warning needs to identify the deprecated object. In the documentation, readers already know which object they're looking at.
So a documentation notice should simply say since which version the object is deprecated and what to use instead, with a link to the replacement.
The extension tries to build this notice from the arguments passed to the
helper. If you need a different notice, you can write one yourself using a
Deprecated: section in the docstring. A hand-written notice always takes
priority.
Sometimes the extension can't get all the information it needs. For example, it
might not be able to read an argument from the source code, or the helper might
only have the runtime warning. In that case, it still adds a notice with
whatever information is available, but also logs a warning. This makes
mkdocs build --strict fail, so you can fix the documentation by writing the
missing notice yourself.
Notices use the deprecated admonition kind by default, the same kind a
hand-written Deprecated: section gets. Your theme needs CSS for it, which the
Frequenz repository template includes. If you use a different admonition style
for deprecations, you can change the kind option. Hand-written notices then
need the same kind, see Hand-written admonitions.
For example, to use the danger style of griffe-warnings-deprecated, with
hand-written notices written as Danger: Deprecated:
plugins:
- mkdocstrings:
handlers:
python:
options:
extensions:
- griffe_frequenz_core.deprecations:
kind: danger
match_title: true
Switching from griffe-warnings-deprecated¤
You can use this extension instead of griffe-warnings-deprecated. This
extension follows the deprecations guide:
- A hand-written notice takes priority over the decorator's message.
- An object is still marked as deprecated if the message can't be read.
- A missing notice produces a warning, even if the decorator has a message.
To switch:
- Remove
griffe_warnings_deprecatedfrom the mkdocstringsextensionslist and removegriffe-warnings-deprecatedfrom your documentation dependencies. - Add
griffe_frequenz_core.deprecationsto theextensionslist. - If you set
kind,titleorlabel, move those options to this extension. If you didn't setkind, notices now use thedeprecatedkind instead ofdanger. Setkind: dangerandmatch_title: trueto keep the old style. - Add a hand-written
Deprecated:notice to each decorated object's docstring.
If you document members inherited from another Frequenz package, that package needs its notices first. They are checked too, see Known limitations.
Don't enable both extensions for the decorator. The other extension inserts the runtime warning as an admonition. This extension can't tell that apart from a hand-written notice, so you could get the runtime warning as your notice, or two notices.
The extension logs a warning if both are enabled, so a strict build fails.
If you want to keep griffe-warnings-deprecated for the decorator, set this
extension's decorator_functions option to an empty list.
Recognized decorators and helpers¤
The extension understands these decorators and helpers:
| Decorator or helper | How it's used | What gets documented |
|---|---|---|
warnings.deprecated |
Used as a decorator | The decorated object |
typing_extensions.deprecated |
Used as a decorator | The decorated object |
frequenz.core.warnings.deprecated_aliases() |
Assigned to a module's __getattr__ |
All aliases in the table |
frequenz.core.warnings.DeprecatedAlias |
An entry in that table | The alias |
frequenz.core.enum.deprecated_member() |
Used as an enum member's value | The enum member |
frequenz.core.enum.DeprecatedMember |
Used as an enum member's value | The enum member |
Griffe resolves imports before matching these names, so aliases work too. For example, this is recognized:
Deprecated classes and functions¤
You can deprecate a class, function, method or property with
@warnings.deprecated on Python 3.13 or later, or
@typing_extensions.deprecated on older versions.
The decorator only takes a runtime warning. Write the documentation notice
yourself, using a Deprecated: section in the docstring:
from typing_extensions import deprecated
@deprecated("mypkg.OldThing is deprecated. Use mypkg.NewThing instead.")
class OldThing:
"""A thing, now called `NewThing`.
Deprecated:
Deprecated since v1.2.0. Use [`NewThing`][mypkg.NewThing] instead.
"""
The extension marks the object as deprecated and moves your notice to the top of its docstring. If you don't write a notice, it shows the decorator's message as Markdown and logs a warning. If it can't read the message either, it uses a generic notice and logs a warning:
Deprecated. It will be removed in a future release.
To deprecate a property, put @deprecated(...) on its getter, below @property.
You can also deprecate an overload, or a property's setter or deleter. mkdocstrings doesn't show their docstrings, so write the notice in the function or property's docstring instead. Say which part is deprecated:
from typing import overload
from typing_extensions import deprecated
@overload
@deprecated(
"Passing an int as factor to mypkg.scale is deprecated. Use a float instead."
)
def scale(factor: int) -> None: ...
@overload
def scale(factor: float) -> None: ...
def scale(factor: int | float) -> None:
"""Scale the thing.
Deprecated:
Passing an `int` is deprecated since v1.2.0. Use a `float` instead.
"""
Here, only the int overload gets a deprecated label and field. The function
as a whole isn't deprecated, so the extension doesn't mark it or move its
notice to the top.
Without a hand-written notice, the extension combines the messages of all deprecated parts into one notice and logs a warning for each part. If it can't read a message, it uses one of these generic notices:
- "One of its overloads is deprecated."
- "Setting it is deprecated."
- "Deleting it is deprecated."
If the whole function or property is deprecated too, its own notice covers its parts.
Deprecated module aliases¤
When you move or rename something, you might want to keep the old name working for a while.
The deprecated_aliases() helper lets you do this by setting a module's
__getattr__. You can also declare the old names under TYPE_CHECKING, so
type checkers can still find them.
Each old name is described by a DeprecatedAlias entry. You can provide:
new_module: The module where the object lives now.new_name: Its new name, if it was renamed.since: The version where the old name became deprecated.message: A custom runtime warning.
You need to provide new_module, new_name or both. In frequenz-core 1.6.0,
since and message are optional. You can pass either, both or neither.
For example:
from typing import TYPE_CHECKING, TypeAlias
from frequenz.core.warnings import DeprecatedAlias, deprecated_aliases
if TYPE_CHECKING:
from mypkg.newmod import Gadget as _Gadget
from mypkg.newmod import Widget as _Widget
Widget: TypeAlias = _Widget
"""A widget that does widget things."""
Doohickey: TypeAlias = _Gadget
"""A gadget, formerly known as `Doohickey`."""
else:
__getattr__ = deprecated_aliases(
__name__,
DeprecatedAlias("Widget", new_module="mypkg.newmod", since="v1.2.0"),
DeprecatedAlias(
"Doohickey", new_module="mypkg.newmod", new_name="Gadget", since="v1.3.0"
),
DeprecatedAlias("Thingamajig", new_name="Widget", since="v1.4.0"),
)
Suppose this code is in mypkg.oldmod. Here's what happens in the generated
documentation:
Widgetgets the notice "Deprecated since v1.2.0. Usemypkg.newmod.Widgetinstead." The replacement is linked, and its value is shown asmypkg.newmod.Widgetinstead of the private_Widget.Doohickeypoints tomypkg.newmod.Gadget, because both the module and the name changed.Thingamajigpoints tomypkg.oldmod.Widget, because only the name changed. Its notice says "UseWidgetinstead.", with a link to that name.
A few other things worth knowing:
- You don't need a
TYPE_CHECKINGdeclaration for every alias. The extension marks all aliases as deprecated. If a name isn't declared underTYPE_CHECKING, it creates a module attribute for it, so the alias still appears in the documentation. - You can customize the notice using
default_message. The extension replaces{since}with the version string exactly as provided. The notice appears next to the alias in the documentation, so it doesn't repeat the deprecated name. It links the replacement using code formatting. - The
messageargument only affects runtime warnings. It doesn't change the documentation notice. If an entry has nosince, the notice only says what to use instead, and the extension logs a warning. To fix this, passsinceor write aDeprecated:section in the docstring underTYPE_CHECKING. - Replacement links use normal cross-references. If a link can't be
resolved,
mkdocs-autorefsreports it. For replacements in another project, add that project'sobjects.invURL to the Python handler'sinventories. - Each alias is processed separately. If the extension can't read one
entry, it skips that entry and continues with the others. Arguments such as
categoryandstackleveldon't affect the documentation. - The helper must be assigned directly to
__getattr__. A customdef __getattr__()that callsdeprecated_aliases()internally won't be recognized. Neither will a__getattr__created in some other way.
Deprecated enum members¤
You can deprecate an enum member by wrapping its value with
deprecated_member() or DeprecatedMember. In frequenz-core 1.6.0, you can
pass new_name to say which member to use instead, and since to say when the
member became deprecated. If there is no replacement, pass a runtime message
and write the notice by hand.
For example:
from frequenz.core.enum import DeprecatedMember, Enum, deprecated_member
class TaskStatus(Enum):
OPEN = 1
PENDING = deprecated_member(1, new_name="OPEN", since="v1.2.0")
WAITING = DeprecatedMember(1, new_name="OPEN")
CANCELLED = deprecated_member(
4,
"mypkg.TaskStatus.CANCELLED is deprecated. Cancelled tasks are deleted now.",
since="v1.3.0",
)
"""The task was cancelled.
Deprecated:
Deprecated since v1.3.0. Cancelled tasks are deleted now.
"""
The extension marks all three members and shows their actual value instead of the
wrapper. For example, the documentation shows PENDING = 1, not the call to
deprecated_member().
Here's how the notices differ:
PENDINGhasnew_nameandsince, so the extension generates its notice usingdefault_message: "Deprecated since v1.2.0. UseOPENinstead."OPENlinks tomypkg.TaskStatus.OPEN. The link only shows the member's name, because it's in the same enum.WAITINGhasnew_namebut nosince. Its notice only says what to use instead, and the extension logs a warning about the missing version.CANCELLEDhas nonew_name, so it needs a hand-written notice. Without one, the extension shows the runtime message as Markdown and logs a warning. BecauseCANCELLEDpassessince, that notice would start with "Deprecated since v1.3.0.", followed by the message.
If you pass both new_name and message, the message only changes the runtime
warning. The extension still builds the notice from new_name and since.
If an argument comes from a variable or a function call, the extension can't read it. It still marks the member as deprecated and shows its value without the wrapper. Unless you write a notice by hand, it uses the information it can read and logs a warning about anything missing. If it can't read any information for the notice, it uses:
Deprecated. It will be removed in a future release.
Hand-written admonitions¤
Sometimes the generated notice isn't enough. For example, you might want to explain how to migrate to a new API or link to a migration guide.
You can do this by adding a deprecation admonition to the object's docstring.
If the extension finds one, it doesn't add another admonition. It still adds
the deprecated label and fills in the deprecated field.
The extension also moves your notice to the top of the docstring, before the summary, so it appears in the same place as a generated notice. You can't write it there yourself, because a docstring must start with its summary.
The extension recognizes your notice by its admonition kind, which must be the
one in the kind option. In a Google-style docstring, the kind is the word
before the colon, in lowercase, with dashes instead of spaces. With the default
kind, that's a Deprecated: section. It can also have its own title, like
Deprecated: Old API. In a numpy-style docstring, a Deprecated section also
counts.
If you use a general kind, like danger, also set match_title: true. Then an
admonition only counts if its title is also the one in the title option
(case-insensitive), like Danger: Deprecated. Other Danger: admonitions are
left alone.
For example:
if TYPE_CHECKING:
Widget: TypeAlias = _Widget
"""A widget that does widget things.
Deprecated:
Deprecated since v1.2.0. Use [`mypkg.newmod.Widget`][] instead, as
explained in the [migration guide](https://example.com/migration).
"""
Use a hand-written notice whenever the extension can't generate a complete one, or when you want to give readers more information.
Known limitations¤
Griffe reads Python source code without running it. This means the extension can't evaluate variables, call functions, or work out values that are only known at runtime. Sometimes it can still mark an object as deprecated, even if it can't read all the arguments of the call.
Here are the main limitations:
-
Module aliases need literal strings. The alias name,
new_module,new_name, andsincemust be written as string literals in the call. If the alias name isn't a literal, the extension can't mark it as deprecated. If another value isn't a literal, the notice leaves out the information it can't read, and the alias value is only shown as the target if the extension can read the target. Themessageargument is never read for module aliases. -
Enum notices need literal strings. The extension can only read
new_name,sinceandmessageif they're string literals. It readsmessageonly whennew_nameisn't passed or can't be read. Constants, function calls, f-strings, and strings joined with+aren't evaluated. Adjacent string literals are fine, because Python joins them automatically. If an argument isn't a literal, the member is still marked as deprecated and its value is shown without the wrapper. The notice uses whatever information the extension can read. -
Alias entries must appear directly in the call. Each entry must be a
DeprecatedAlias(...)call insidedeprecated_aliases(). Entries stored in variables or unpacked from a collection can't be read. For example, neither of these entries will be marked:
-
Arguments can't be unpacked. Calls to
deprecated_member(),DeprecatedMember, andDeprecatedAliasmust use explicit arguments, not*argsor**kwargs. For example, a member defined asdeprecated_member(*ARGS)is still marked as deprecated, with a generic message, but its value is shown as the whole call. For aliases, unpacked keyword arguments mean only the alias name can be read. If positional arguments are unpacked, the alias isn't marked at all. -
Overloads need a function to show their notice. Griffe attaches overloads to the function defined after them. If they're declared only in a stub file, they still get a label and field, but no visible notice.
-
Decorator messages need non-empty literal strings. If the message isn't a non-empty string literal, or the arguments use
*args, the object gets a generic notice. A decorator used without a call, like@deprecated, fails at runtime. So does a call whose arguments don't match the signature, for example@deprecated(message="Gone"). These still mark the object with a generic notice and log a warning, even with a hand-written notice. -
The extension doesn't validate your code. It matches arguments the same way Python would when calling the function. If the arguments don't match the function's signature, the call is skipped, except for decorators, which still mark the object with a generic notice. The extension doesn't check whether the argument values are valid. That's a job for your tests, which should catch invalid calls when the module is imported.
All these limitations produce warnings when they affect the generated
documentation. This lets mkdocs build --strict catch problems instead of
silently generating incomplete documentation.
For example, you'll get a warning if:
- A notice is missing the deprecation version or replacement.
- A runtime warning is used as the documentation notice.
- A deprecated value can't be shown correctly.
- A deprecation can't be marked at all.
Writing your own deprecation admonition fixes warnings about missing or incomplete notices, but not other problems.
All these warnings are only logged when the object's docstring is parsed for
rendering. Griffe may visit code that never appears in your documentation. For
example, loading a namespace package like frequenz also visits other installed
packages using that namespace. Their problems shouldn't make your build fail.
An alias entry that can't be read isn't documented as an object, so its warning
is logged when the docstring of the module with the alias table is parsed.
The extension only logs warnings for code in the packages listed in
checked_packages, which is frequenz by default. Your documentation can still
show code from other packages, for example members inherited from a class in a
dependency. The extension documents their deprecations the same way, using the
decorator's message when there is no hand-written notice. It only logs their
problems at debug level, since only their own project can fix them.
Members are checked where they are defined, so a member inherited from another Frequenz package is checked too. Its warning points to the class that defines it, and has to be fixed in that package.
If you want to know why the extension couldn't read something, run
mkdocs build --verbose. The extension logs those details at debug level.
Broken links to replacements are reported separately by mkdocs-autorefs.
Options¤
| Option | Default | Effect |
|---|---|---|
kind |
deprecated |
The kind of the admonition, which is also its CSS class. Hand-written notices need the same kind. Use lowercase, with dashes instead of spaces. |
title |
Deprecated |
The title of the admonition. An empty title or null means no title. |
match_title |
false |
Hand-written notices also need the configured title. Needs a title. |
label |
deprecated |
The label added to deprecated objects. null means no label. |
checked_packages |
frequenz |
The packages, with their subpackages, whose problems are logged as warnings. |
decorator_functions |
warnings.deprecated, typing_extensions.deprecated |
The paths of the decorators that deprecate a class or function. |
alias_table_functions |
frequenz.core.warnings.deprecated_aliases |
The paths of the functions that create a module __getattr__. |
alias_classes |
frequenz.core.warnings.DeprecatedAlias |
The paths of the callables that create one alias entry. |
member_wrapper_functions |
frequenz.core.enum.deprecated_member, frequenz.core.enum.DeprecatedMember |
The paths of the callables that wrap a deprecated enum member's value. |
default_message |
Deprecated since {since}. Use {new_link} instead. |
The notice template for aliases and enum members with new_name. See the placeholders below. |
show_target |
true |
Show an alias' value as its target, instead of the private name. |
You can use these placeholders in default_message:
{old}: The fully qualified path of the deprecated object.{new}: The fully qualified path of its replacement.{new_link}: A link to the replacement in code font. If the replacement is in the same module or enum, the link only shows its name.{since}: The version string, as written in the call.
The four path options are lists. If you set one, it replaces the default. To
use your own helper as well as the frequenz-core one, list both:
extensions:
- griffe_frequenz_core.deprecations:
alias_table_functions:
- frequenz.core.warnings.deprecated_aliases
- mypkg.compat.moved_to
checked_packages is a list too. Write a list even for a single name, like
checked_packages: [frequenz]. If you set any of these five options to a
string, the extension raises an error, instead of reading each letter as a name.
Your own decorators and helpers need to take the same arguments as the ones they replace, because the extension reads their calls the same way:
- Decorators work like
deprecated(message, /, *, category=DeprecationWarning, stacklevel=1). The message must be positional. The other arguments must be passed by keyword. - Alias tables work like
deprecated_aliases(module, /, *aliases). Every positional argument after the module is an alias entry. Keyword arguments are ignored. - Alias entries work like
DeprecatedAlias(name, /, *, new_module=None, new_name=None, since=None, message=None). The name is positional, and everything else is passed by keyword. You need to passnew_module,new_nameor both.sinceandmessageare optional and independent. PassingNoneis the same as not passing the argument. - Enum member wrappers work like
deprecated_member(value, message=None, *, new_name=None, since=None). You can pass the value and message positionally or by keyword.new_nameandsincemust be keyword arguments. You need to passmessage,new_nameor both. PassingNonefor an optional argument is the same as not passing it.
If frequenz-core renames or moves a helper, you can update these options with
the new path. You don't need to wait for a new release of this package.
There is one difference from griffe-warnings-deprecated, on purpose. If
title is empty, griffe-warnings-deprecated puts the message in the
admonition title, but this extension doesn't. The notice contains a link to the
replacement, which doesn't belong in a title.
Supported Platforms¤
The following platforms are officially supported (tested):
- Python: 3.11 through 3.15
- Operating System: Ubuntu Linux 20.04
- Architectures: amd64, arm64
Contributing¤
If you want to know how to build this project and contribute to it, please check out the Contributing Guide.